﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Threading;
using System.IO.Ports;
using System.Net;
using Excel = Microsoft.Office.Interop.Excel;
using static System.Windows.Forms.ListViewItem;

namespace Battery
{
    public partial class Form1 : Form
    {
        //private Timer Timer;
        public enum Language
        {
            ChineseSimplified,//简体中文
            English //英语
            //....如果有别的语言，另外添加
        }

        //当前选择的语言
        private Language CurrentSelectedLanguage = Language.ChineseSimplified;
        int m_testMode = 1;
        OleDbConnection conn = null;
        OleDbConnection conn1 = null;
        MasterRTU ModbusRtu = null;
        private SerialPort sp = new SerialPort();
        Thread thread_poll = null;
        Thread thread_poll2 = null;
        Thread thread_poll3 = null;
        
        int m_SelectIndex = 0;
        bool m_bStart = false;
        private string strcom = "COM1";
        private string strbaud = "9600";
        private string strdatabit = "8";
        private string strparity = "None";
        private string strstopbit = "One";
        private bool m_Runing = false;
        private bool isShowCapacity = false;
        bool m_isPortOpen = false;
        byte m_iDeviceAddr = 1;
        bool m_first = false;
        private bool m_DebugRight = false;
        private bool m_SystemRight = false;
        public delegate void InsertTestRecordToList(string volt, string temp, string neizu, byte index, string capacity, string capacity2);
        public delegate void ShowTestInfo(string volt, string curr, string temp1, string temp2, string count, string version, string strDeviceTime, string strCapacity, string strDisTime, string strAvgVolt, string strAvgTemp, string strAvgNeizu, string strChCurStus, string strNeiZuTestStus, string strNeiZuUpdateTime);
        public delegate void ShowTimeInfo(string devTime, string localTime);
        public delegate void ShowChargeAverage(string AvgVolt, string AvgTemp,string AvgNeizu);
        public delegate void ConfirmListCount(byte count);
        public delegate void ShowYanFaDebug(string Xiangxi, string Version, string TotalVolt, string Value1, string Value2, string Value3, string Value4, string Value5, int index);
        public delegate void InsertToList(ListView listView, string strIndex, string Volt, string Temp, string NeiZu, int index);
        public delegate void InsertToList2(string NeiZu, int index);
        public delegate void InsertToList3(ListView listView, string strDesc,string Value, int index);
        public delegate void ShowAlarmInfo(string ErrorDesc, int index, int value);
        public delegate void ShowDataToControlText(ushort[] registerhold);
        public delegate void ShowMonthListView(int index);
        public delegate void SetResistanceDelegate(string neizu, byte index);
        public delegate void SetDataGridView5(ushort i,ushort []recv);
        public delegate void SetDataGridView5_1(ushort i, ushort[] recv);
        bool isRunning5 = false;
        bool isRunning6 = false;
        bool isRunning8 = false;
        bool isRunning11 = false;
        bool isRunningHistory0 = false;
        string strLabel6 = "";
        const string Success = "成功";  //内阻设置系数时的状态
        const string Failure = "失败";
        const string General = "";
        ushort[] originalResistance = null;//单体模块的原始内阻  未进行运算过的 【bat1】
        double[] originalTemp = null;//单体模块的原始温度=实际温度-温差 进行运算过的 【bat1】
        ushort[] reviseResistance = null;//单体模块的修正阻值比例  按照【bat2，bat1】为一个两个字节的ushort存放
        ushort[] reviseTemp = null;//单体模块的修正温度  按照【bat2，bat1】为一个两个字节的ushort存放
        int BatGroup = 0;//默认电池组1
        string dateTimeStringInGridView5 = string.Empty;//画时间的字符串
        int x1, x2;                                     //画字的坐标左右范围                        
        private void ChangeListLange()
        {
             Language lang = this.CurrentSelectedLanguage;
             string strLang = lang.ToString();
             //////////////////////////////获取时间
             if (strLang == "ChineseSimplified")
             {
                 listView1.Columns[0].Text = "电池序号";
                 listView1.Columns[1].Text = "电压(V) ";
                 listView1.Columns[2].Text = "温度(℃)";
                 listView1.Columns[3].Text = "内阻(mΩ)";
                 listView1.Columns[4].Text = "容量(%)";
                 listView1.Columns[5].Text = "容量(AH)";

                 listView2.Columns[0].Text = "序号";
                 listView2.Columns[1].Text = "电池序号";;
                 listView2.Columns[2].Text = "电压(V) ";
                 listView2.Columns[3].Text = "温度(℃)";
                 listView2.Columns[4].Text = "内阻(mΩ)";

                 listView3.Columns[0].Text = "序号";
                 listView3.Columns[1].Text = "电池序号"; ;
                 listView3.Columns[2].Text = "电压(V) ";
                 listView3.Columns[3].Text = "温度(℃)";
                 listView3.Columns[4].Text = "内阻(mΩ)";

                 listView4.Columns[0].Text = "序号";
                 listView4.Columns[1].Text = "电池序号"; ;
                 listView4.Columns[2].Text = "电压(V) ";
                 listView4.Columns[3].Text = "温度(℃)";
                 listView4.Columns[4].Text = "内阻(mΩ)";

                 listView5.Columns[0].Text = "序号";
                 listView5.Columns[1].Text = "电池序号"; ;
                 listView5.Columns[2].Text = "电压(V) ";
                 listView5.Columns[3].Text = "温度(℃)";
                 listView5.Columns[4].Text = "内阻(mΩ)";

                 listView6.Columns[0].Text = "序号";
                 listView6.Columns[1].Text = "电池序号"; ;
                 listView6.Columns[2].Text = "电压(V) ";
                 listView6.Columns[3].Text = "温度(℃)";
                 listView6.Columns[4].Text = "内阻(mΩ)";


                 listView7.Columns[0].Text = "序号";
                 listView7.Columns[1].Text = "电池序号"; ;
                 listView7.Columns[2].Text = "电压(V) ";
                 listView7.Columns[3].Text = "温度(℃)";
                 listView7.Columns[4].Text = "内阻(mΩ)";


                 listView8.Columns[0].Text = "序号";
                 listView8.Columns[1].Text = "起始时间 ";
                 listView8.Columns[2].Text = "报警值(HEX)";
                 listView8.Columns[3].Text = "报警详情";

                 listView9.Columns[0].Text = "序号";
                 listView9.Columns[1].Text = "起始时间 ";
                 listView9.Columns[2].Text = "截止时间 ";
                 listView9.Columns[3].Text = "报警值(HEX)";
                 listView9.Columns[4].Text = "报警详情";

                 listView10.Columns[0].Text = "序号";
                 listView10.Columns[1].Text = "详情描述";
                 listView10.Columns[2].Text = "数据值";


                 listView11.Columns[0].Text = "序号";
                 listView11.Columns[1].Text = "参数";
                 listView11.Columns[2].Text = "软件版本";
                 listView11.Columns[3].Text = "电池总电压(V)";
                 listView11.Columns[4].Text = "VC模块测量电压值";
                 listView11.Columns[5].Text = "ICT通道1电压(V)";
                 listView11.Columns[6].Text = "ICT通道2电压(V)";
                 listView11.Columns[7].Text = "ICT通道3电压(V)";
                 listView11.Columns[8].Text = "ICT通道4电压(V)";


                 comboBox6.Items[0] = "模式0";
                 comboBox6.Items[1] = "模式1";
                 comboBox6.Items[2] = "模式2";
                 comboBox6.Items[3] = "模式3";
                 comboBox6.Items[4] = "模式4";
                 comboBox6.Items[5] = "模式5";

                 dataGridView2.Columns[0].HeaderText = "电流模块";
                 dataGridView2.Columns[1].HeaderText = "使能选项";
                 dataGridView2.Columns[2].HeaderText = "电流通道";
                 dataGridView2.Columns[3].HeaderText = "传感器类型";
                 dataGridView2.Columns[4].HeaderText = "电池组号";
                 dataGridView2.Columns[5].HeaderText = "电流量程";
                 dataGridView2.Columns[6].HeaderText = "单位";

                 dataGridView1.Columns[0].HeaderText = "序号";
                 dataGridView1.Columns[1].HeaderText = "名称";
                 dataGridView1.Columns[2].HeaderText = "阻值";
                 dataGridView1.Columns[3].HeaderText = "单位";

             
                 comboBox9.Items[0] = "内阻报警倍率报警";
                 comboBox9.Items[1] = "单体内阻过高报警";

                 comboBox10.Items[0] = "屏蔽报警";
                 comboBox10.Items[1] = "使能报警";

                 comboBox11.Items[0] = "屏蔽报警";
                 comboBox11.Items[1] = "使能报警";

                 comboBox12.Items[0] = "屏蔽报警";
                 comboBox12.Items[1] = "使能报警";

                 comboBox13.Items[0] = "屏蔽报警";
                 comboBox13.Items[1] = "使能报警";

                 comboBox14.Items[0] = "屏蔽报警";
                 comboBox14.Items[1] = "使能报警";

                 comboBox15.Items[0] = "屏蔽报警";
                 comboBox15.Items[1] = "使能报警";

                 comboBox16.Items[0] = "屏蔽报警";
                 comboBox16.Items[1] = "使能报警";

                 comboBox17.Items[0] = "屏蔽报警";
                 comboBox17.Items[1] = "使能报警";

                 comboBox18.Items[0] = "屏蔽报警";
                 comboBox18.Items[1] = "使能报警";

                 comboBox19.Items[0] = "屏蔽报警";
                 comboBox19.Items[1] = "使能报警";

                 comboBox20.Items[0] = "屏蔽报警";
                 comboBox20.Items[1] = "使能报警";

                 comboBox21.Items[0] = "屏蔽报警";
                 comboBox21.Items[1] = "使能报警";

                 comboBox22.Items[0] = "屏蔽报警";
                 comboBox22.Items[1] = "使能报警";

                 comboBox23.Items[0] = "屏蔽报警";
                 comboBox23.Items[1] = "使能报警";

                 comboBox24.Items[0] = "屏蔽报警";
                 comboBox24.Items[1] = "使能报警";

                 comboBox25.Items[0] = "屏蔽报警";
                 comboBox25.Items[1] = "使能报警";

                 comboBox26.Items[0] = "屏蔽报警";
                 comboBox26.Items[1] = "使能报警";

                 comboBox27.Items[0] = "屏蔽报警";
                 comboBox27.Items[1] = "使能报警";

                 comboBox28.Items[0] = "屏蔽报警";
                 comboBox28.Items[1] = "使能报警";

            }
             else
             {
                 listView1.Columns[0].Text = "BAT NUM";
                 listView1.Columns[1].Text = "Voltage(V) ";
                 listView1.Columns[2].Text = "Temperature(℃)";
                 listView1.Columns[3].Text = "Internal RES(mΩ)";
                 listView1.Columns[4].Text = "Capacity(%)";
                 listView1.Columns[5].Text = "Capacity(AH)";

                 listView2.Columns[0].Text = "Index";
                 listView2.Columns[1].Text = "BAT NUM"; ;
                 listView2.Columns[2].Text = "Voltage(V) ";
                 listView2.Columns[3].Text = "Temp(℃)";
                 listView2.Columns[4].Text = "INTL RES(mΩ)";

                 listView3.Columns[0].Text = "Index";
                 listView3.Columns[1].Text = "BAT NUM"; ;
                 listView3.Columns[2].Text = "Voltage(V) ";
                 listView3.Columns[3].Text = "Temp(℃)";
                 listView3.Columns[4].Text = "INTL RES(mΩ)";

                 listView4.Columns[0].Text = "Index";
                 listView4.Columns[1].Text = "BAT NUM"; ;
                 listView4.Columns[2].Text = "Voltage(V) ";
                 listView4.Columns[3].Text = "Temp(℃)";
                 listView4.Columns[4].Text = "INTL RES(mΩ)";

                 listView5.Columns[0].Text = "Index";
                 listView5.Columns[1].Text = "BAT NUM"; ;
                 listView5.Columns[2].Text = "Voltage(V) ";
                 listView5.Columns[3].Text = "Temp(℃)";
                 listView5.Columns[4].Text = "INTL RES(mΩ)";

                 listView6.Columns[0].Text = "Index";
                 listView6.Columns[1].Text = "BAT NUM"; ;
                 listView6.Columns[2].Text = "Voltage(V) ";
                 listView6.Columns[3].Text = "Temp(℃)";
                 listView6.Columns[4].Text = "INTL RES(mΩ)";

                 listView7.Columns[0].Text = "Index";
                 listView7.Columns[1].Text = "BAT NUM"; ;
                 listView7.Columns[2].Text = "Voltage(V) ";
                 listView7.Columns[3].Text = "Temp(℃)";
                 listView7.Columns[4].Text = "INTL RES(mΩ)";

                 listView8.Columns[0].Text = "Index";
                 listView8.Columns[1].Text = "Start time ";
                 listView8.Columns[2].Text = "Alarm value(HEX)";
                 listView8.Columns[3].Text = "Alarm Details";

                 listView9.Columns[0].Text = "Index";
                 listView9.Columns[1].Text = "Start time ";
                 listView9.Columns[2].Text = "Deadline ";
                 listView9.Columns[3].Text = "Alarm value(HEX)";
                 listView9.Columns[4].Text = "Alarm Details";

                 listView10.Columns[0].Text = "Index";
                 listView10.Columns[1].Text = "Detailed";
                 listView10.Columns[2].Text = "Data value";


                 listView11.Columns[0].Text = "Index";
                 listView11.Columns[1].Text = "Parameter";
                 listView11.Columns[2].Text = "SW version";
                 listView11.Columns[3].Text = "Total bat volt(V)";
                 listView11.Columns[4].Text = "VC module Volt";
                 listView11.Columns[5].Text = "ICT Chan1 volt(V)";
                 listView11.Columns[6].Text = "ICT Chan2 volt(V)";
                 listView11.Columns[7].Text = "ICT Chan3 volt(V)";
                 listView11.Columns[8].Text = "ICT Chan4 volt(V)";

                 comboBox6.Items[0] = "Mode10";
                 comboBox6.Items[1] = "Model1";
                 comboBox6.Items[2] = "Model2";
                 comboBox6.Items[3] = "Model3";
                 comboBox6.Items[4] = "Model4";
                 comboBox6.Items[5] = "Model5";

                 dataGridView2.Columns[0].HeaderText = "Curr module";
                 dataGridView2.Columns[1].HeaderText = "ENA options";
                 dataGridView2.Columns[2].HeaderText = "Curr chan";
                 dataGridView2.Columns[3].HeaderText = "Sensor type";
                 dataGridView2.Columns[4].HeaderText = "Bat pack num";
                 dataGridView2.Columns[5].HeaderText = "Curr range";
                 dataGridView2.Columns[6].HeaderText = "Unit";

                 dataGridView1.Columns[0].HeaderText = "Index";
                 dataGridView1.Columns[1].HeaderText = "Name";
                 dataGridView1.Columns[2].HeaderText = "Resistance value";
                 dataGridView1.Columns[3].HeaderText = "Unit";

                 comboBox9.Items[0] = "RES ALM Magn ALM";
                 comboBox9.Items[1] = "ALM for high RES";

                 comboBox10.Items[0] = "Shielding ALM";
                 comboBox10.Items[1] = "Enable ALM";

                 comboBox11.Items[0] = "Shielding ALM";
                 comboBox11.Items[1] = "Enable ALM";

                 comboBox12.Items[0] = "Shielding ALM";
                 comboBox12.Items[1] = "Enable ALM";

                 comboBox13.Items[0] = "Shielding ALM";
                 comboBox13.Items[1] = "Enable ALM";

                 comboBox14.Items[0] = "Shielding ALM";
                 comboBox14.Items[1] = "Enable ALM";

                 comboBox15.Items[0] = "Shielding ALM";
                 comboBox15.Items[1] = "Enable ALM";

                 comboBox16.Items[0] = "Shielding ALM";
                 comboBox16.Items[1] = "Enable ALM";

                 comboBox17.Items[0] = "Shielding ALM";
                 comboBox17.Items[1] = "Enable ALM";

                 comboBox18.Items[0] = "Shielding ALM";
                 comboBox18.Items[1] = "Enable ALM";

                 comboBox19.Items[0] = "Shielding ALM";
                 comboBox19.Items[1] = "Enable ALM";

                 comboBox20.Items[0] = "Shielding ALM";
                 comboBox20.Items[1] = "Enable ALM";

                 comboBox21.Items[0] = "Shielding ALM";
                 comboBox21.Items[1] = "Enable ALM";

                 comboBox22.Items[0] = "Shielding ALM";
                 comboBox22.Items[1] = "Enable ALM";

                 comboBox23.Items[0] = "Shielding ALM";
                 comboBox23.Items[1] = "Enable ALM";

                 comboBox24.Items[0] = "Shielding ALM";
                 comboBox24.Items[1] = "Enable ALM";

                 comboBox25.Items[0] = "Shielding ALM";
                 comboBox25.Items[1] = "Enable ALM";

                 comboBox26.Items[0] = "Shielding ALM";
                 comboBox26.Items[1] = "Enable ALM";

                 comboBox27.Items[0] = "Shielding ALM";
                 comboBox27.Items[1] = "Enable ALM";

                 comboBox28.Items[0] = "Shielding ALM";
                 comboBox28.Items[1] = "Enable ALM";
            }

        }
         public Form1()
        {
            InitializeComponent();

            Control.CheckForIllegalCrossThreadCalls = false;

            ModbusRtu = new MasterRTU();

            scanLocalDevicePorts();//获取当前设备可用串口

            listView1.Columns.Add("电池序号", 80, HorizontalAlignment.Left);//向listView1中添加“文件名称”列
            listView1.Columns.Add("电压(V) ", 150, HorizontalAlignment.Left);//向listView1中添加“文件名称”列
            listView1.Columns.Add("温度(℃)", 150, HorizontalAlignment.Left);//向listView1中添加“创建时间”列
            listView1.Columns.Add("内阻(mΩ)", 150, HorizontalAlignment.Left);//向listView1中添加“创建时间”列
            listView1.Columns.Add("容量(%)", 150, HorizontalAlignment.Left);//向listView1中添加“创建时间”列
            listView1.Columns.Add("容量(AH)", 150, HorizontalAlignment.Left);//向listView1中添加“创建时间”列
            listView1.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular);
            listView1.Scrollable = true;//有滚动条

            listView2.Columns.Add("序号", 50, HorizontalAlignment.Left);
            listView2.Columns.Add("电池序号", 60, HorizontalAlignment.Left);//向listView1中添加“文件名称”列
            listView2.Columns.Add("电压(V) ", 85, HorizontalAlignment.Left);//向listView1中添加“文件名称”列
            listView2.Columns.Add("温度(℃)", 85, HorizontalAlignment.Left);//向listView1中添加“创建时间”列
            listView2.Columns.Add("内阻(mΩ)", 95, HorizontalAlignment.Left);//向listView1中添加“创建时间”列

            listView2.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular);
            listView2.Scrollable = true;//有滚动条

            listView3.Columns.Add("序号", 50, HorizontalAlignment.Left);
            listView3.Columns.Add("电池序号", 60, HorizontalAlignment.Left);//向listView1中添加“文件名称”列
            listView3.Columns.Add("电压(V) ", 82, HorizontalAlignment.Left);//向listView1中添加“文件名称”列
            listView3.Columns.Add("温度(℃)", 82, HorizontalAlignment.Left);//向listView1中添加“创建时间”列
            listView3.Columns.Add("内阻(mΩ)", 95, HorizontalAlignment.Left);//向listView1中添加“创建时间”列

            listView3.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular);
            listView3.Scrollable = true;//有滚动条

            listView4.Columns.Add("序号", 50, HorizontalAlignment.Left);
            listView4.Columns.Add("电池序号", 60, HorizontalAlignment.Left);//向listView1中添加“文件名称”列
            listView4.Columns.Add("电压(V) ", 85, HorizontalAlignment.Left);//向listView1中添加“文件名称”列
            listView4.Columns.Add("温度(℃)", 85, HorizontalAlignment.Left);//向listView1中添加“创建时间”列
            listView4.Columns.Add("内阻(mΩ)", 95, HorizontalAlignment.Left);//向listView1中添加“创建时间”列

            listView4.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular);
            listView4.Scrollable = true;//有滚动条

            listView5.Columns.Add("序号", 50, HorizontalAlignment.Left);
            listView5.Columns.Add("电池序号", 60, HorizontalAlignment.Left);//向listView1中添加“文件名称”列
            listView5.Columns.Add("电压(V) ", 82, HorizontalAlignment.Left);//向listView1中添加“文件名称”列
            listView5.Columns.Add("温度(℃)", 82, HorizontalAlignment.Left);//向listView1中添加“创建时间”列
            listView5.Columns.Add("内阻(mΩ)", 95, HorizontalAlignment.Left);//向listView1中添加“创建时间”列

            listView5.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular);
            listView5.Scrollable = true;//有滚动条

            listView6.Columns.Add("序号", 50, HorizontalAlignment.Left);
            listView6.Columns.Add("电池序号", 60, HorizontalAlignment.Left);//向listView1中添加“文件名称”列
            listView6.Columns.Add("电压(V) ", 85, HorizontalAlignment.Left);//向listView1中添加“文件名称”列
            listView6.Columns.Add("温度(℃)", 85, HorizontalAlignment.Left);//向listView1中添加“创建时间”列
            listView6.Columns.Add("内阻(mΩ)", 95, HorizontalAlignment.Left);//向listView1中添加“创建时间”列

            listView6.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular);
            listView6.Scrollable = true;//有滚动条

            listView7.Columns.Add("序号", 50, HorizontalAlignment.Left);
            listView7.Columns.Add("电池序号", 60, HorizontalAlignment.Left);//向listView1中添加“文件名称”列
            listView7.Columns.Add("电压(V) ", 85, HorizontalAlignment.Left);//向listView1中添加“文件名称”列
            listView7.Columns.Add("温度(℃)", 85, HorizontalAlignment.Left);//向listView1中添加“创建时间”列
            listView7.Columns.Add("内阻(mΩ)", 95, HorizontalAlignment.Left);//向listView1中添加“创建时间”列

            listView7.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular);
            listView7.Scrollable = true;//有滚动条


            listView8.Columns.Add("序号", 80, HorizontalAlignment.Left);//向listView1中添加“文件名称”列
            listView8.Columns.Add("起始时间 ", 150, HorizontalAlignment.Left);//向listView1中添加“文件名称”列
            listView8.Columns.Add("报警值(HEX)", 100, HorizontalAlignment.Left);//向listView1中添加“创建时间”列
            listView8.Columns.Add("报警详情", 500, HorizontalAlignment.Left);//向listView1中添加“创建时间”列

            listView8.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular);
            listView8.Scrollable = true;//有滚动条

            listView9.Columns.Add("序号", 80, HorizontalAlignment.Left);//向listView1中添加“文件名称”列
            listView9.Columns.Add("起始时间 ", 160, HorizontalAlignment.Left);//向listView1中添加“文件名称”列
            listView9.Columns.Add("截止时间 ", 160, HorizontalAlignment.Left);//向listView1中添加“文件名称”列
            listView9.Columns.Add("报警值(HEX)", 120, HorizontalAlignment.Left);//向listView1中添加“创建时间”列
            listView9.Columns.Add("报警详情", 320, HorizontalAlignment.Left);//向listView1中添加“创建时间”列

            listView9.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular);
            listView9.Scrollable = true;//有滚动条


            listView10.Columns.Add("序号", 50, HorizontalAlignment.Left);//向listView1中添加“文件名称”列
            listView10.Columns.Add("详情描述", 420, HorizontalAlignment.Left);//向listView1中添加“文件名称”列
            listView10.Columns.Add("数据值", 150, HorizontalAlignment.Left);//向listView1中添加“创建时间”列
            listView10.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular);
            listView10.Scrollable = true;//有滚动条

            listView11.Columns.Add("序号", 45, HorizontalAlignment.Left);//向listView1中添加“文件名称”列
            listView11.Columns.Add("参数", 115, HorizontalAlignment.Left);//向listView1中添加“文件名称”列
            listView11.Columns.Add("软件版本", 100, HorizontalAlignment.Left);//向listView1中添加“创建时间”列
            listView11.Columns.Add("电池总电压(V)", 120, HorizontalAlignment.Left);//向listView1中添加“创建时间”列
            listView11.Columns.Add("VC模块测量电压值", 130, HorizontalAlignment.Left);//向listView1中添加“创建时间”列
            listView11.Columns.Add("ICT通道1电压(V)", 130, HorizontalAlignment.Left);//向listView1中添加“创建时间”列
            listView11.Columns.Add("ICT通道2电压(V)", 130, HorizontalAlignment.Left);//向listView1中添加“创建时间”列
            listView11.Columns.Add("ICT通道3电压(V)", 130, HorizontalAlignment.Left);//向listView1中添加“创建时间”列
            listView11.Columns.Add("ICT通道4电压(V)", 130, HorizontalAlignment.Left);//向listView1中添加“创建时间”列
            listView11.Font = new System.Drawing.Font("宋体", 11F, System.Drawing.FontStyle.Regular);
            listView11.Scrollable = true;//有滚动条

            //隐藏超级管理员角色的页面
            setTabPageVisable(1);

           // Me.ColumnHeader2.TextAlign = System.Windows.Forms.HorizontalAlignment.Center
            // listVie
            //获取上次存储的语言，进行界面的更新

            string language = Properties.Settings.Default.DefaultLanguage;

            MultiLanguage.SetDefaultLanguage(language);

            MultiLanguage.LoadLanguage(this, typeof(Form1));

            switch (language.ToLower())
            {
                case "zh-cn": this.CurrentSelectedLanguage = Language.ChineseSimplified; break;
                case "en-us": this.CurrentSelectedLanguage = Language.English; break;
                default:
                    break;
            }
            setTabPageVisable(0);
        }
        public string GetBeijingTime()
        {

            WebRequest request = null;
            WebResponse response = null;
            WebHeaderCollection headerCollection = null;
            string datetime = string.Empty;
            try
            {
                request = WebRequest.Create("https://www.baidu.com");
                request.Timeout = 3000;
                request.Credentials = CredentialCache.DefaultCredentials;
                response = (WebResponse)request.GetResponse();
                headerCollection = response.Headers;
                foreach (var h in headerCollection.AllKeys)
                { if (h == "Date") { datetime = headerCollection[h]; } }
                return datetime;
            }
            catch (Exception) { return datetime; }
            finally
            {
                if (request != null)
                { request.Abort(); }
                if (response != null)
                { response.Close(); }
                if (headerCollection != null)
                { headerCollection.Clear(); }
            }


        }
        private bool InitConnectDatabase1()
        {
            string strModuleExcel = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;

            strModuleExcel = strModuleExcel + "Database" + "\\Results.mdb";

            string CONN_STRING_STDREG32 = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;  Jet OLEDB:Database Password=pwd12345; Data Source={0}",
                     strModuleExcel);

            conn1 = new OleDbConnection(CONN_STRING_STDREG32);

            try
            {
                conn1.Open();

            }
            catch
            {
                conn1.Close();
                MessageBox.Show("数据库打开失败!", "提示");
                return false;
            }
            return true;
        }
        private bool InitConnectDatabase()
        {
            string strModuleExcel = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;

            strModuleExcel = strModuleExcel + "Database" + "\\ERT.mdb";

            string CONN_STRING_STDREG32 = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;  Jet OLEDB:Database Password=pwd12345; Data Source={0}",
                     strModuleExcel);

            conn = new OleDbConnection(CONN_STRING_STDREG32);

            try
            {
                conn.Open();

            }
            catch
            {
                conn.Close();
                MessageBox.Show("数据库打开失败!", "提示");
                return false;
            }
            return true;
        }
        public string GetDataVauleToStep(string TableName, string RowName)
        {
            string sql = "select * from " + TableName;

            DataSet testdatevalue = GetItemDataSet(sql);

            if (testdatevalue == null)
            {
                return "";
            }

            string value = testdatevalue.Tables[0].Rows[0][RowName].ToString();

            return value;
        }
        private DataSet GetItemDataSet(string strCmd)
        {
            DataSet dataset = new DataSet();
            try
            {
                // conn.Open();
                OleDbCommand cmd = new OleDbCommand();
                cmd.CommandText = strCmd;
                cmd.Connection = conn;

                OleDbDataAdapter adp = new OleDbDataAdapter(cmd);
                adp.Fill(dataset);
            }
            catch
            {
                //conn.Close();
                return null;
            }

            //conn.Close();
            return dataset;
        }


        public bool UpdateTableInfo(string TableName, string wherename, string wherevalue, string RowName, string Value)
        {

            string Sql = "UPDATE " + TableName + " SET " + RowName + "='" + Value + "' where " + wherename + "='" + wherevalue + "'";

            OleDbCommand cmd = new OleDbCommand(Sql, conn);
            try
            {
                cmd.ExecuteNonQuery();
                return true;
            }
            catch
            {
                MessageBox.Show("update error", "提示");
                return false;
            }
        }
        public bool UpdateTableInfo(string TableName, string RowName, string Value)
        {

            string Sql = "UPDATE " + TableName + " SET " + RowName + "='" + Value + "'";

            OleDbCommand cmd = new OleDbCommand(Sql, conn);
            try
            {
                cmd.ExecuteNonQuery();
                return true;
            }
            catch
            {
                MessageBox.Show("update error");
                return false;
            }
        }

        private void scanLocalDevicePorts()//获取当前设备可用串口
        {
            string[] ports = System.IO.Ports.SerialPort.GetPortNames();
            comboBox1.Items.Clear();
            foreach(string port in ports)
            {
                comboBox1.Items.Add(port);
            }
        }
        private void comboBox1_DropDown(object sender, EventArgs e)
        {
            scanLocalDevicePorts();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            strcom = comboBox1.Text;
            strbaud = comboBox2.Text;
            strdatabit = comboBox3.Text;
            strparity = comboBox4.Text;
            strstopbit = comboBox5.Text;

            try
            {

                OpenSerialCom();
             
            }
            catch (Exception ex)
            {
                MessageBox.Show("打开串口失败!", "提示");
            }

            UpdateTableInfo("ComSet", "ComPort", comboBox1.Text);
            UpdateTableInfo("ComSet", "Baud", comboBox2.Text);
            UpdateTableInfo("ComSet", "Databits", comboBox3.Text);
            UpdateTableInfo("ComSet", "Parity", comboBox4.Text);
            UpdateTableInfo("ComSet", "Stopbits", comboBox5.Text);
        }
        public void OpenSerialCom()
        {
            try
            {
                Language lang = this.CurrentSelectedLanguage;
                string strLang = lang.ToString();
                
                
                ModbusRtu.Close();

                bool bopen = ModbusRtu.Open(strcom, int.Parse(strbaud), int.Parse(strdatabit), (Parity)Enum.Parse(typeof(Parity), strparity, true), (StopBits)Enum.Parse(typeof(StopBits), strstopbit, true),checkBox_DTR.Checked,checkBox_RTS.Checked);
                if (!bopen)
                {
                    label6.ForeColor = Color.Red;    
                    m_isPortOpen = false;
                    if (strLang == "ChineseSimplified")
                    {
                        label6.Text = strcom + " 打开失败!";
                        MessageBox.Show(label6.Text, "提示");
                    }
                    else
                    {
                        label6.Text = strcom + " Open f!";
                        MessageBox.Show(label6.Text, "Tips");
                    }
                }
                else
                {
                    label6.ForeColor = Color.Green;
                    if (strLang == "ChineseSimplified")
                    {
                        label6.Text = strcom + " 已打开!";
                       // MessageBox.Show(label6.Text, "提示");
                    }
                    else
                    {
                        label6.Text = strcom + " Opened!";
                        //MessageBox.Show(label6.Text, "Tips");
                    }
                    m_isPortOpen = true;
                }
            }
            catch (Exception ex)
            {
                label6.ForeColor = Color.Red;
                label6.Text = strcom + " open fail!";
                MessageBox.Show(label6.Text,"tips");
                m_isPortOpen = false;
            }
        }
        private void ChangeToLabel()
        {
            label6.Text=strLabel6;
            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            if (strLang == "ChineseSimplified")
            {
                label6.Text = label6.Text.Replace("Open fial", " 打开失败");
                label6.Text = label6.Text.Replace("Opened", " 已打开");
                label19.Text = label19.Text.Replace("Commun error", " 通信错误");
             
              
            }
            else
            {
                label6.Text = label6.Text.Replace("打开失败", " Open fial");
                label6.Text = label6.Text.Replace("已打开", " Opened");
                label19.Text = label19.Text.Replace("通信错误", "Commun error");
            }
        }
        public bool Open(string portName, int baudRate, int databits, Parity parity, StopBits stopBits)
        {
            //Ensure port isn't already opened:
            if (!sp.IsOpen)
            {
                //Assign desired settings to the serial port:
                sp.PortName = portName;
                sp.BaudRate = baudRate;
                sp.DataBits = databits;
                sp.Parity = parity;
                sp.StopBits = stopBits;
                //These timeouts are default and cannot be editted through the class at this point:
                //sp.ReadTimeout = 604800;
                sp.ReadTimeout = 1000;
                sp.WriteTimeout = 604800;

                try
                {
                    sp.Open();
                }
                catch (Exception err)
                {
                    //  modbusStatus = "Error opening " + portName + ": " + err.Message;
                    return false;
                }
                // modbusStatus = portName + " opened successfully";
                return true;
            }
            else
            {
                // modbusStatus = portName + " already opened";
                return false;
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {

        }
        private void Timer_Tick(object sender, EventArgs e)
        {
            //this.label1.Text = DateTime.Now.ToString("HH:mm:ss");
            
            //DateTime current = DateTime.Now.ToLocalTime();
           // this.label15.Text = current.ToString("yyyy年MM月dd dddd HH时mm分ss秒");

           
        }
        private void Form1_Load(object sender, EventArgs e)
        {

            ushort value11 = 0xFFFF, value111A = 1, value222A = 0;
            //byte b = (byte)~value11;
            ushort groupValue = 5;
            value111A = (ushort)(value11 & groupValue);
            value111A = (ushort)(value111A & 255);
            //value111A = (ushort)(value111A | (1 << 15));
            value222A = (ushort)(value111A & ~(1 << 15));
            if (value111A > 0 || value222A == 0)
            {
                //value111A = (ushort)(value111A & groupValue);
            }

            ushort value333 = 3000;
            short value111 = 32767;
            
            string strTemp = "1.5";

            byte aaa = Convert.ToByte(Convert.ToSingle(strTemp)*10);

            ushort value222 = 300;
            if (value333 == 10)
            {
 
            }
            
            ushort value = 0x01;
            ushort value2 = 0x08;
            value = (ushort)(0x01 << 8 | value2);

          
           // timer1.Interval = 1000;
            //timer1.Tick += new EventHandler(Timer_Tick);
            timer1.Start();

            if (!InitConnectDatabase()) return;

            comboBox1.Text = GetDataVauleToStep("ComSet", "ComPort");
            comboBox2.Text = GetDataVauleToStep("ComSet", "Baud");
            comboBox3.Text = GetDataVauleToStep("ComSet", "Databits");
            comboBox4.Text = GetDataVauleToStep("ComSet", "Parity");
            comboBox5.Text = GetDataVauleToStep("ComSet", "Stopbits");

            //textBox28.Text = GetDataVauleToStep("ComSet", "Addr1");
           
            m_iDeviceAddr = 1;

            for (int i = 1; i < 101; i++)
            {
                domainUpDown1.Items.Add(i);
            }
            
            strcom = GetDataVauleToStep("ComSet", "ComPort");
            strbaud = GetDataVauleToStep("ComSet", "Baud");
            strdatabit = GetDataVauleToStep("ComSet", "Databits");
            strparity = GetDataVauleToStep("ComSet", "Parity");
            strstopbit = GetDataVauleToStep("ComSet", "Stopbits");

            //单体版本所用的datagridView
            for (int i = 0; i <= 29; i++)
            {
                DataGridViewRow row = new DataGridViewRow();
                row.CreateCells(dataGridView6);
                dataGridView6.Rows.Add(row);
            }
            for (int i = 1; i <= 120; i++)
            {
                if (i <= 30)
                {
                    dataGridView6.Rows[i - 1].Cells[0].Value = i.ToString();
                }
                else if (i >= 31 && i <= 60)
                {
                    dataGridView6.Rows[i-1-30].Cells[2].Value = i.ToString();

                }
                else if (i >= 61 && i <= 90)
                {
                    dataGridView6.Rows[i - 1 - 60].Cells[4].Value = i.ToString();

                }
                else if (i >= 91 && i <= 120)
                {
                    dataGridView6.Rows[i - 1 - 90].Cells[6].Value = i.ToString();

                }

            }
           
            //m_iDeviceAddr = 12;

            domainUpDown1.SelectedIndex = 0;

            try
            {
                OpenSerialCom();//打开串口
                if (m_isPortOpen)
                {
                    ushort[] registerhold = new ushort[1];
                    bool bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 2000, 1, ref registerhold);//版本
                    if (bhold)
                    {

                        label19.ForeColor = Color.Blue;
                        label19.Text = registerhold[0].ToString();

                    }
                    else
                    {
                        label19.ForeColor = Color.Red;

                        Language lang = this.CurrentSelectedLanguage;
                        string strLang = lang.ToString();
                         if (strLang == "ChineseSimplified")
                         {
                             label19.Text = "通信错误!";
                         }
                         else
                         {
                             label19.Text = "Commun error!";
                         }

                    }
                }


              


                /*if (thread_poll != null)
                {
                    if (!thread_poll.IsAlive)
                    {
                        thread_poll = new Thread(new ThreadStart(Poll_Thread));
                        thread_poll.Start();
                    }
                }
                else
                {
                    thread_poll = new Thread(new ThreadStart(Poll_Thread));
                    thread_poll.Start();
                }*/

                InsertToDataGridView();
                InsertToSysConfig();
                InitConnectDatabase1();
                ShowAlarmHistoryList(1);
                dateTimePicker1.Value = DateTime.Now.AddDays(-1);

                ChangeListLange();

             //   System.Threading.Thread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US");
              
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
   
        private void InsertToSysConfig()      
        {
            dataGridView2.Rows.Clear();
            
            DataTable dt = new DataTable();
            dt.Columns.Add("1");
            dt.Columns.Add("2");
            dt.Columns.Add("3");
            dt.Columns.Add("4");
            dt.Columns.Add("5");
            dt.Columns.Add("6");
            dt.Columns.Add("7");

            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            //////////////////////////////获取时间
            if (strLang == "ChineseSimplified")
            {

                Column9.Items[0] = "开启";
                Column9.Items[1] = "关闭";

                Column11.Items[0] = "充放电流传感器";
                Column11.Items[1] = "浮充电流传感器";

                Column12.Items[0] = "不关联";
                Column12.Items[1] = "第1组";
                Column12.Items[2] = "第2组";
                Column12.Items[3] = "第3组";
                Column12.Items[4] = "第4组";
                Column12.Items[5] = "第5组";
                Column12.Items[6] = "第6组";
                
                
                
                dt.Rows.Add("系统采集模块", "开启", "ICT1", "充放电流传感器", "第1组", "100", "A");
                dt.Rows.Add("系统采集模块", "开启", "ICT2", "充放电流传感器", "第1组", "100", "mA");

                dt.Rows.Add("#199VC模块", "开启", "ICT1", "充放电流传感器", "第1组", "100", "A");
                dt.Rows.Add("#199VC模块", "开启", "ICT2", "浮充电流传感器", "第1组", "100", "mA");
                dt.Rows.Add("#199VC模块", "开启", "ICT3", "充放电流传感器", "第1组", "100", "A");
                dt.Rows.Add("#199VC模块", "开启", "ICT4", "充放电流传感器", "第1组", "100", "mA");

                dt.Rows.Add("#198VC模块", "开启", "ICT1", "充放电流传感器", "第1组", "100", "A");
                dt.Rows.Add("#198VC模块", "开启", "ICT2", "充放电流传感器", "第1组", "100", "mA");
                dt.Rows.Add("#198VC模块", "开启", "ICT3", "充放电流传感器", "第1组", "100", "A");
                dt.Rows.Add("#198VC模块", "开启", "ICT4", "充放电流传感器", "第1组", "100", "mA");

                dt.Rows.Add("#197VC模块", "开启", "ICT1", "充放电流传感器", "第1组", "100", "A");
                dt.Rows.Add("#197VC模块", "开启", "ICT2", "充放电流传感器", "第1组", "100", "mA");
                dt.Rows.Add("#197VC模块", "开启", "ICT3", "充放电流传感器", "第1组", "100", "A");
                dt.Rows.Add("#197VC模块", "开启", "ICT4", "充放电流传感器", "第1组", "100", "mA");

                dt.Rows.Add("#196VC模块", "开启", "ICT1", "充放电流传感器", "第1组", "100", "A");
                dt.Rows.Add("#196VC模块", "开启", "ICT2", "充放电流传感器", "第1组", "100", "mA");
                dt.Rows.Add("#196VC模块", "开启", "ICT3", "充放电流传感器", "第1组", "100", "A");
                dt.Rows.Add("#196VC模块", "开启", "ICT4", "充放电流传感器", "第1组", "100", "mA");
                //row.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

                this.dataGridView2.DataSource = dt;
                this.dataGridView2.ColumnHeadersHeight = 40;
                this.dataGridView2.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
                this.dataGridView2.MergeColumnNames.Add("Column8");
                //this.dataGridView2.MergeColumnNames.Add("Column2");
                this.dataGridView2.AddSpanHeader(0, 7, "电流采样模式设置");
            }
            else
            {

                /*DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)dataGridView2.Rows[3].Cells[1];
                DataGridViewComboBoxCell cell2 = (DataGridViewComboBoxCell)dataGridView2.Rows[7].Cells[1];
                DataGridViewComboBoxCell cell3 = (DataGridViewComboBoxCell)dataGridView2.Rows[11].Cells[1];
                DataGridViewComboBoxCell cell4 = (DataGridViewComboBoxCell)dataGridView2.Rows[15].Cells[1];
                cell.Items[0] = "Open";
                cell.Items[1] = "Closed";
                cell2.Items[0] = "Open";
                cell2.Items[1] = "Closed";
                cell3.Items[0] = "Open";
                cell3.Items[1] = "Closed";
                cell4.Items[0] = "Open";
                cell4.Items[1] = "Closed";
                for (int i = 0; i < 18; i++)
                {

                    if (i == 1) continue;

                    DataGridViewComboBoxCell cell11 = (DataGridViewComboBoxCell)dataGridView2.Rows[i].Cells[3];
                    cell11.Items[0] = "Chg-dischg CUR SEN";
                    cell11.Items[1] = "Float CUR SEN";

                    DataGridViewComboBoxCell cell22 = (DataGridViewComboBoxCell)dataGridView2.Rows[i].Cells[4];
                    cell22.Items[0] = "Unassociated";
                    cell22.Items[1] = "Group1";
                    cell22.Items[2] = "Group2";
                    cell22.Items[3] = "Group3";
                    cell22.Items[4] = "Group4";
                    cell22.Items[5] = "Group5";
                    cell22.Items[6] = "Group6";
                }*/
                Column9.Items[0] = "Open";
                Column9.Items[1] = "Closed";

                Column11.Items[0] = "Chg-dischg CUR SEN";
                Column11.Items[1] = "Float CUR SEN";

                Column12.Items[0] = "Unassociated";
                Column12.Items[1] = "Group1";
                Column12.Items[2] = "Group2";
                Column12.Items[3] = "Group3";
                Column12.Items[4] = "Group4";
                Column12.Items[5] = "Group5";
                Column12.Items[6] = "Group6";
                
                dt.Rows.Add("Sys ACQ module", "Open", "ICT1", "Chg-dischg CUR SEN", "Group1", "100", "A");
                dt.Rows.Add("Sys ACQ module", "Open", "ICT2", "Chg-dischg CUR SEN", "Group2", "100", "mA");

                dt.Rows.Add("#199VCMod", "Open", "ICT1", "Chg-dischg CUR SEN", "Group1", "100", "A");
                dt.Rows.Add("#199VCMod", "Open", "ICT2", "Float CUR SEN", "Group1", "100", "mA");
                dt.Rows.Add("#199VCMod", "Open", "ICT3", "Chg-dischg CUR SEN", "Group1", "100", "A");
                dt.Rows.Add("#199VCMod", "Open", "ICT4", "Chg-dischg CUR SEN", "Group1", "100", "mA");

                dt.Rows.Add("#198VCMod", "Open", "ICT1", "Chg-dischg CUR SEN", "Group1", "100", "A");
                dt.Rows.Add("#198VCMod", "Open", "ICT2", "Chg-dischg CUR SEN", "Group1", "100", "mA");
                dt.Rows.Add("#198VCMod", "Open", "ICT3", "Chg-dischg CUR SEN", "Group1", "100", "A");
                dt.Rows.Add("#198VCMod", "Open", "ICT4", "Chg-dischg CUR SEN", "Group1", "100", "mA");

                dt.Rows.Add("#197VCMod", "Open", "ICT1", "Chg-dischg CUR SEN", "Group1", "100", "A");
                dt.Rows.Add("#197VCMod", "Open", "ICT2", "Chg-dischg CUR SEN", "Group1", "100", "mA");
                dt.Rows.Add("#197VCMod", "Open", "ICT3", "Chg-dischg CUR SEN", "Group1", "100", "A");
                dt.Rows.Add("#197VCMod", "Open", "ICT4", "Chg-dischg CUR SEN", "Group1", "100", "mA");

                dt.Rows.Add("#196VCMod", "Open", "ICT1", "Chg-dischg CUR SEN", "Group1", "100", "A");
                dt.Rows.Add("#196VCMod", "Open", "ICT2", "Chg-dischg CUR SEN", "Group1", "100", "mA");
                dt.Rows.Add("#196VCMod", "Open", "ICT3", "Chg-dischg CUR SEN", "Group1", "100", "A");
                dt.Rows.Add("#196VCMod", "Open", "ICT4", "Chg-dischg CUR SEN", "Group1", "100", "mA");
          
                //row.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

                this.dataGridView2.DataSource = dt;
                this.dataGridView2.ColumnHeadersHeight = 40;
                this.dataGridView2.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
                this.dataGridView2.MergeColumnNames.Add("Column8");
                //this.dataGridView2.MergeColumnNames.Add("Column2");
                this.dataGridView2.AddSpanHeader(0, 7, "CUR ACQ mode set");


               
            }
            
            //this.dataGridView2.Rows[0].Cells[1].Value = "";
            this.dataGridView2.Rows[0].Cells[1].ReadOnly = true;
            //DataGridViewComboBoxCell 
            DataGridViewTextBoxCell textbox = new DataGridViewTextBoxCell();
            textbox.Value = "1111";
            this.dataGridView2.Rows[0].Cells[1].ReadOnly = true;
           // this.dataGridView1.Rows[1].Cells[2].col
        }
        private void ChangedataGridView2Lange()
        {
               Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            //////////////////////////////获取时间
            string strValue = this.dataGridView2.Rows[3].Cells[1].Value.ToString();//显示值
            string strValue1 = this.dataGridView2.Rows[7].Cells[1].Value.ToString();//显示值
            string strValue2 = this.dataGridView2.Rows[11].Cells[1].Value.ToString();//显示值
            string strValue3 = this.dataGridView2.Rows[15].Cells[1].Value.ToString();//显示值
            if (strLang == "ChineseSimplified")
            {
       
                strValue=strValue.Replace("Open","开启");
                strValue=strValue.Replace("Closed","关闭");

                strValue1=strValue1.Replace("Open","开启");
                strValue1=strValue1.Replace("Closed","关闭");

                strValue2=strValue2.Replace("Open","开启");
                strValue2=strValue2.Replace("Closed","关闭");

                strValue3=strValue3.Replace("Open","开启");
                strValue3=strValue3.Replace("Closed","关闭");


                this.dataGridView2.Rows[3].Cells[1].Value = strValue;    
                this.dataGridView2.Rows[7].Cells[1].Value = strValue1;  
                this.dataGridView2.Rows[11].Cells[1].Value = strValue2;  
                this.dataGridView2.Rows[15].Cells[1].Value = strValue3;  
           
                for (int i = 0; i < 18; i++)
                {

                    if (i == 1) continue;                   
                    string strValue4 = this.dataGridView2.Rows[i].Cells[3].Value.ToString();//显示值
                    strValue4=strValue4.Replace("Chg-dischg CUR SEN","充放电流传感器");
                    strValue4=strValue4.Replace("Float CUR SEN","浮充电流传感器");
                    
                    this.dataGridView2.Rows[i].Cells[3].Value = strValue4;
                 
                     string strValue5= this.dataGridView2.Rows[i].Cells[4].Value.ToString();//显示值
                     strValue5 = strValue5.Replace("Unassociated", "不关联");
                     strValue5 = strValue5.Replace("Group1", "第1组");
                     strValue5 = strValue5.Replace("Group2", "第2组");
                     strValue5 = strValue5.Replace("Group3", "第3组");
                     strValue5 = strValue5.Replace("Group4", "第4组");
                     strValue5 = strValue5.Replace("Group5", "第5组");
                     strValue5 = strValue5.Replace("Group6", "第6组");
                      this.dataGridView2.Rows[i].Cells[4].Value = strValue5;
                 }
             }
            else
            {
                strValue = strValue.Replace("开启", "Open");
                strValue = strValue.Replace("关闭", "Closed");

                strValue1 = strValue1.Replace("开启", "Open");
                strValue1 = strValue1.Replace("关闭", "Closed");

                strValue2 = strValue2.Replace("开启", "Open");
                strValue2 = strValue2.Replace("关闭", "Closed");

                strValue3 = strValue3.Replace("开启", "Open");
                strValue3 = strValue3.Replace("关闭", "Closed");


                this.dataGridView2.Rows[3].Cells[1].Value = strValue;
                this.dataGridView2.Rows[7].Cells[1].Value = strValue1;
                this.dataGridView2.Rows[11].Cells[1].Value = strValue2;
                this.dataGridView2.Rows[15].Cells[1].Value = strValue3;

                for (int i = 0; i < 18; i++)
                {

                    if (i == 1) continue;
                    string strValue4 = this.dataGridView2.Rows[i].Cells[3].Value.ToString();//显示值
                    strValue4 = strValue4.Replace("充放电流传感器", "Chg-dischg CUR SEN");
                    strValue4 = strValue4.Replace("浮充电流传感器", "Float CUR SEN");

                    this.dataGridView2.Rows[i].Cells[3].Value = strValue4;

                    string strValue5 = this.dataGridView2.Rows[i].Cells[4].Value.ToString();//显示值
                    strValue5 = strValue5.Replace("不关联", "Unassociated");
                    strValue5 = strValue5.Replace("第1组", "Group1");
                    strValue5 = strValue5.Replace("第2组", "Group2");
                    strValue5 = strValue5.Replace("第3组", "Group3");
                    strValue5 = strValue5.Replace("第4组", "Group4");
                    strValue5 = strValue5.Replace("第5组", "Group5");
                    strValue5 = strValue5.Replace("第6组", "Group6");
                    this.dataGridView2.Rows[i].Cells[4].Value = strValue5;
                }
            }
        }
        private void InsertToSysConfig2()
        {
           

            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            //////////////////////////////获取时间
            if (strLang == "ChineseSimplified")
            {

                Column9.Items[0] = "开启";
                Column9.Items[1] = "关闭";

                Column11.Items[0] = "充放电流传感器";
                Column11.Items[1] = "浮充电流传感器";

                Column12.Items[0] = "不关联";
                Column12.Items[1] = "第1组";
                Column12.Items[2] = "第2组";
                Column12.Items[3] = "第3组";
                Column12.Items[4] = "第4组";
                Column12.Items[5] = "第5组";
                Column12.Items[6] = "第6组";

            }
            else
            {

                
                Column9.Items[0] = "Open";
                Column9.Items[1] = "Closed";

                Column11.Items[0] = "Chg-dischg CUR SEN";
                Column11.Items[1] = "Float CUR SEN";

                Column12.Items[0] = "Unassociated";
                Column12.Items[1] = "Group1";
                Column12.Items[2] = "Group2";
                Column12.Items[3] = "Group3";
                Column12.Items[4] = "Group4";
                Column12.Items[5] = "Group5";
                Column12.Items[6] = "Group6";
                
            }
        
        }
        private void DataGridView_3_4_SetLanguageText()
        {
            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            //////////////////////////////获取时间
            if (strLang == "ChineseSimplified")
            {
             

            }
            else
            {
                //dataGridView 3
                Column15.HeaderText = "Battery serial numbe";
                Column16.HeaderText = "Read internal resistance (mΩ)";
                Column17.HeaderText = "Target internal resistance (mΩ)";
                Column18.HeaderText = "correction factor";
                Column19.HeaderText = "Operation";
                Column20.HeaderText = "State";
                //dataGridView4
                Column21.HeaderText = "Battery serial numbe";
                Column22.HeaderText = "Read temperature(℃)";
                Column23.HeaderText = "target temperature(℃)";
                Column24.HeaderText = "correction factor(℃)";
                Column25.HeaderText = "Operation";
                Column26.HeaderText = "State";

                comboBox_historyType.Items[0] = "Alarm history data";
                comboBox_historyType.Items[1] = "Single section voltage history data";
                comboBox_historyType.Items[2] = "Single section temperature historical data";
                comboBox_historyType.Items[3] = "Single section internal resistance historical data";
                comboBox_historyType.Items[4] = "Historical data about the capacity of a single section";
                //
                Column27.HeaderText = "group";
                Column28.HeaderText = "serial";
                Column29.HeaderText = "value";
                Column30.HeaderText = "serial";
                Column31.HeaderText = "value";
                Column32.HeaderText = "serial";
                Column33.HeaderText = "value";
                Column34.HeaderText = "serial";
                Column35.HeaderText = "value";
                Column36.HeaderText = "serial";
                Column37.HeaderText = "value";
                //
                comboBox29.Items[0] = "Single section internal resistance historical data";
                comboBox29.Items[1] = "state of charge";
                comboBox29.Items[2] = "state of discharge";

                listView12.Items[0].SubItems[0].Text = "Internal resistance last measured time";

                listView12.Items[1].SubItems[0].Text = "Battery serial numbe";
                listView12.Items[2].SubItems[0].Text = "Number of historical internal resistance bars";

                listView12.Columns[1].Text = "serial number";
                listView12.Columns[3].Text = "serial number";
                listView12.Columns[5].Text = "serial number";
                listView12.Columns[7].Text = "serial number";
                listView12.Columns[9].Text = "serial number";

            }
        }
        private void InsertToNeizuchuValue(string NeiZu, int index)
        {
            //string strName = index.ToString();
            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            //////////////////////////////获取时间
           
            if (dataGridView1.RowCount < index + 1)
            {
                int index1 = this.dataGridView1.Rows.Add();
                this.dataGridView1.Rows[index1].Cells[0].Value = (index + 1).ToString();
                if (strLang == "ChineseSimplified")
                    this.dataGridView1.Rows[index1].Cells[1].Value = "#" + (index + 1).ToString() + "初值内阻";
                else
                this.dataGridView1.Rows[index1].Cells[1].Value = "#" + (index + 1).ToString() + "INIT VAL of RES "; 
                this.dataGridView1.Rows[index1].Cells[2].Value = NeiZu;
                this.dataGridView1.Rows[index1].Cells[3].Value = "mΩ";
            }
            else
            {
                if (strLang == "ChineseSimplified")
                    this.dataGridView1.Rows[index].Cells[1].Value = "#" + (index + 1).ToString() + "初值内阻";
                else
                    this.dataGridView1.Rows[index].Cells[1].Value = "#" + (index + 1).ToString() + "INIT VAL of RES "; 

                this.dataGridView1.Rows[index].Cells[2].Value = NeiZu;
            }

        }
        private void InsertToTheMaxAndMinValue(ListView listView,string strIndex,string Volt, string Temp, string NeiZu,int index)
        {
            //string strName = index.ToString();
            if (listView.Items.Count < index + 1)
            {
                //ListViewItem OptionItem = new ListViewItem(strName);
                ListViewItem OptionItem = new ListViewItem((index + 1).ToString());
                OptionItem.UseItemStyleForSubItems = false;
                OptionItem.SubItems.Add(strIndex);//
                OptionItem.SubItems.Add(Volt);//
                OptionItem.SubItems.Add(Temp);//
                OptionItem.SubItems.Add(NeiZu);//

              
                listView.Items.Add(OptionItem);//执行添加操作*/
            }
            else
            {
                listView.Items[index].SubItems[1].Text = strIndex;
                listView.Items[index].SubItems[2].Text = Volt;
                listView.Items[index].SubItems[3].Text = Temp;
                listView.Items[index].SubItems[4].Text = NeiZu;
            }

        }
        private void ShowChargeAverageText(string AvgVolt, string AvgTemp,string AvgNeizu)
        {
            textBox75.Text=AvgVolt;
            textBox74.Text = AvgTemp;
            textBox73.Text = AvgNeizu;
        }
        private void ReadTheMaxAndMinValue()
        {
            //public delegate void ShowYanFaDebug(string Xiangxi, string Value, int index);
            try
            {
                isRunning5 = true;
                bool bhold = false;
                int index = 0;
                // ushort value = 0x01;

                ushort value = 0x01;
                float value2 = 0;

                string strIndex = "";
                string Volt = "";
                string Temp = "";
                string NeiZu= "";

                string AvgVolt="";
                string AvgTemp="";
                string AvgNeizu = "";

                ushort[] registerhold = new ushort[40];


                bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 5, 3, ref registerhold);//
                value = registerhold[0];
                value2 = (float)(value) / 1000;
                AvgVolt = value2.ToString("0.000");

                value = registerhold[1];
                value2 = (float)(value) / 10;
                AvgTemp = value2.ToString("0.0");

                value = registerhold[2];
                value2 = (float)(value) / 1000;
                AvgNeizu = value2.ToString("0.000");
                Invoke(new ShowChargeAverage(ShowChargeAverageText), new object[] { AvgVolt, AvgTemp, AvgNeizu });
      

                bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 500, 40, ref registerhold);//
                // ShowTestCount();
                if (bhold)
                {
                    for (int i = 0; i < 40; i += 4)
                    {

                        if (i < 20)
                        {

                            strIndex = registerhold[i].ToString();
                            value = registerhold[i + 1];
                            value2 = (float)(value) / 1000;
                            Volt = value2.ToString("0.000");

                            value = registerhold[i + 2];
                            value2 = (float)(value) / 10;
                            Temp = value2.ToString("0.00");

                            value = registerhold[i + 3];
                            value2 = (float)(value) / 1000;
                            NeiZu = value2.ToString("0.00");
                            //  Invoke(new ShowYanFaDebug(InsertToDebugList), new object[] { xiangxi, Version, ChargeTotalVolt, Value1, Value2, Value3, Value4, index });
                            Invoke(new InsertToList(InsertToTheMaxAndMinValue), new object[] { listView2, strIndex, Volt, Temp, NeiZu, index });
                            index++;

                        }
                        else
                        {
                            if (i == 20) index = 0;
                            
                            strIndex = registerhold[i].ToString();

                            value = registerhold[i + 1];
                            value2 = (float)(value) / 1000;
                            Volt = value2.ToString("0.000");

                            value = registerhold[i + 2];
                            value2 = (float)(value) / 10;
                            Temp = value2.ToString("0.00");

                            value = registerhold[i + 3];
                            value2 = (float)(value) / 1000;
                            NeiZu = value2.ToString("0.00");
                            //  Invoke(new ShowYanFaDebug(InsertToDebugList), new object[] { xiangxi, Version, ChargeTotalVolt, Value1, Value2, Value3, Value4, index });
                            Invoke(new InsertToList(InsertToTheMaxAndMinValue), new object[] { listView3, strIndex, Volt, Temp, NeiZu, index });
                            index++;

                        }
                    }
                }
                index = 0;
                ////温度最值
                bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 600, 40, ref registerhold);//
                // ShowTestCount();
                if (bhold)
                {
                    for (int i = 0; i < 40; i += 4)
                    {

                        if (i < 20)
                        {

                            strIndex = registerhold[i].ToString();
                            value = registerhold[i + 1];
                            value2 = (float)(value) / 1000;
                            Volt = value2.ToString("0.000");

                            value = registerhold[i + 2];
                            value2 = (float)(value) / 10;
                            Temp = value2.ToString("0.00");

                            value = registerhold[i + 3];
                            value2 = (float)(value) / 1000;
                            NeiZu = value2.ToString("0.00");
                            //  Invoke(new ShowYanFaDebug(InsertToDebugList), new object[] { xiangxi, Version, ChargeTotalVolt, Value1, Value2, Value3, Value4, index });
                            Invoke(new InsertToList(InsertToTheMaxAndMinValue), new object[] { listView4, strIndex, Volt, Temp, NeiZu, index });
                            index++;

                        }
                        else
                        {
                            if (i == 20) index = 0;

                            strIndex = registerhold[i].ToString();

                            value = registerhold[i + 1];
                            value2 = (float)(value) / 1000;
                            Volt = value2.ToString("0.000");

                            value = registerhold[i + 2];
                            value2 = (float)(value) / 10;
                            Temp = value2.ToString("0.00");

                            value = registerhold[i + 3];
                            value2 = (float)(value) / 1000;
                            NeiZu = value2.ToString("0.00");
                            //  Invoke(new ShowYanFaDebug(InsertToDebugList), new object[] { xiangxi, Version, ChargeTotalVolt, Value1, Value2, Value3, Value4, index });
                            Invoke(new InsertToList(InsertToTheMaxAndMinValue), new object[] { listView5, strIndex, Volt, Temp, NeiZu, index });
                            index++;

                        }
                    }
                }
                //电池内阻最值
                index = 0;
                bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 700, 40, ref registerhold);//
                // ShowTestCount();
                if (bhold)
                {
                    for (int i = 0; i < 40; i += 4)
                    {

                        if (i < 20)
                        {

                            strIndex = registerhold[i].ToString();
                            value = registerhold[i + 1];
                            value2 = (float)(value) / 1000;
                            Volt = value2.ToString("0.000");

                            value = registerhold[i + 2];
                            value2 = (float)(value) / 10;
                            Temp = value2.ToString("0.00");

                            value = registerhold[i + 3];
                            value2 = (float)(value) / 1000;
                            NeiZu = value2.ToString("0.00");
                            //  Invoke(new ShowYanFaDebug(InsertToDebugList), new object[] { xiangxi, Version, ChargeTotalVolt, Value1, Value2, Value3, Value4, index });
                            Invoke(new InsertToList(InsertToTheMaxAndMinValue), new object[] { listView6, strIndex, Volt, Temp, NeiZu, index });
                            index++;

                        }
                        else
                        {
                            if (i == 20) index = 0;

                            strIndex = registerhold[i].ToString();

                            value = registerhold[i + 1];
                            value2 = (float)(value) / 1000;
                            Volt = value2.ToString("0.000");

                            value = registerhold[i + 2];
                            value2 = (float)(value) / 10;
                            Temp = value2.ToString("0.00");

                            value = registerhold[i + 3];
                            value2 = (float)(value) / 1000;
                            NeiZu = value2.ToString("0.00");
                            //  Invoke(new ShowYanFaDebug(InsertToDebugList), new object[] { xiangxi, Version, ChargeTotalVolt, Value1, Value2, Value3, Value4, index });
                            Invoke(new InsertToList(InsertToTheMaxAndMinValue), new object[] { listView7, strIndex, Volt, Temp, NeiZu, index });
                            index++;

                        }
                    }
                }

            }
            catch (Exception ex)
            {
                // MessageBox.Show(ex.ToString());
            }
            isRunning5 = false;
            // isRunning5 = false;
        }
        private void InsertToDebugList(string Xiangxi, string Version, string TotalVolt, string Value1, string Value2, string Value3, string Value4, string Value5, int index)
        {
            
            //string strName = index.ToString();
            if (listView11.Items.Count < index + 1)
            {
                
                
                //ListViewItem OptionItem = new ListViewItem(strName);
                ListViewItem OptionItem = new ListViewItem((index + 1).ToString());
                OptionItem.UseItemStyleForSubItems = false;
                OptionItem.SubItems.Add(Xiangxi);//
                OptionItem.SubItems.Add(Version);//
                OptionItem.SubItems.Add(TotalVolt);//
                OptionItem.SubItems.Add(Value1);//
                OptionItem.SubItems.Add(Value2);//
                OptionItem.SubItems.Add(Value3);//
                OptionItem.SubItems.Add(Value4);//
                OptionItem.SubItems.Add(Value5);//
                listView11.Items.Add(OptionItem);//执行添加操作*/
            }
            else
            {
                listView11.Items[index].SubItems[1].Text = Xiangxi;
                listView11.Items[index].SubItems[2].Text = Version;
                listView11.Items[index].SubItems[3].Text = TotalVolt;
                listView11.Items[index].SubItems[4].Text = Value1;
                listView11.Items[index].SubItems[5].Text = Value2;
                listView11.Items[index].SubItems[6].Text = Value3;
                listView11.Items[index].SubItems[7].Text = Value4;
                listView11.Items[index].SubItems[8].Text = Value5;
            }
        }
        private void ReadRDDebug()
        {
            //public delegate void ShowYanFaDebug(string Xiangxi, string Value, int index);
            try
            {

                isRunning11 = true;
                //listView1.Items.Clear();
                //ShowTempAndShiDu
                //isRunning3 = true;
                bool bhold = false;
                int index = 0;
                // ushort value = 0x01;

                ushort value = 0x01;
                ushort value2 = 0x01;
                float value3 = 0;

                string xiangxi = "";
                string Value1 = "";
                string Value2 = "";
                string Value3= "";
                string Value4 = "";
                string Value5 = "";
                string ChargeTotalVolt = "";
                string Version = "";
                ushort[] registerhold = new ushort[68];
                Language lang = this.CurrentSelectedLanguage;
                string strLang = lang.ToString();         
                bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 1400, 32, ref registerhold);//
               // ShowTestCount();
                if (bhold)
                {
                    for (int i = 0; i < 32; i += 8)
                    {

                 
                          if (strLang == "ChineseSimplified")
                          {
                              if (index == 0)
                                  xiangxi = "#199模块数据";
                              if (index == 1)
                                  xiangxi = "#198模块数据";
                              if (index == 2)
                                  xiangxi = "#197模块数据";
                              if (index == 3)
                                  xiangxi = "#196模块数据";
                          }
                          else
                          {
                              if (index == 0)
                                  xiangxi = "#199 Module data";
                              if (index == 1)
                                  xiangxi = "#198 Module data";
                              if (index == 2)
                                  xiangxi = "#197 Module data";
                              if (index == 3)
                                  xiangxi = "#196 Module data";
                          }

                        Version = registerhold[i].ToString();

                        value = registerhold[i+6];
                        value2 = registerhold[i+7];
                        value = (ushort)(value << 8 | value2);
                        value3 = (float)(value) / 1000;
                        ChargeTotalVolt = value3.ToString("0.000");


                        value = registerhold[i + 1];
                        value3 = (float)(value) / 10;
                        Value1 = value3.ToString("0.0");

                        value = registerhold[i + 2];
                        value3 = (float)(value) / 1000;
                        Value2 = value3.ToString("0.000");

                        value = registerhold[i + 3];
                        value3 = (float)(value) / 1000;
                        Value3 = value3.ToString("0.000");

                        value = registerhold[i + 4];
                        value3 = (float)(value) / 1000;
                        Value4 = value3.ToString("0.000");

                        value = registerhold[i + 5];
                        value3 = (float)(value) / 1000;
                        Value5 = value3.ToString("0.000");

                        Invoke(new ShowYanFaDebug(InsertToDebugList), new object[] { xiangxi, Version, ChargeTotalVolt, Value1, Value2, Value3, Value4, Value5, index });
                        index++;                       
                                         
                    }


                }



            }
            catch (Exception ex)
            {
                // MessageBox.Show(ex.ToString());
            }
            isRunning11 = false;
           // isRunning5 = false;
        }
        private void InsertToDataGridView()
        {
            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            string Desc = "";
            for (int i = 0; i < 120; i++)
            {
                DataGridViewRow row = new DataGridViewRow();
                row.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                int index = dataGridView1.Rows.Add(row);

                if (strLang == "ChineseSimplified")
                   Desc = "#" + (index+1).ToString() + "初值内阻";
                else
                   Desc = "#" + (index + 1).ToString() + "INIT VAL of RES "; 
                

                dataGridView1.Rows[index].Cells[0].Value = (index+1).ToString();

                dataGridView1.Rows[index].Cells[1].Value = Desc;

                dataGridView1.Rows[index].Cells[2].Value = "7325";

                dataGridView1.Rows[index].Cells[3].Value = "mΩ";
      
            }

        }
        private void button3_Click(object sender, EventArgs e)
        {
                 button3.Enabled = false;

                 Language lang = this.CurrentSelectedLanguage;
                    string strLang = lang.ToString();
                    //////////////////////////////获取时间
                if (m_isPortOpen)
                {

                    ushort[] registerhold = new ushort[1];
                    bool bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 2000, 1, ref registerhold);//版本
                    if (!bhold)
                    {
                        if (strLang == "ChineseSimplified")
                        MessageBox.Show("通信错误,请检查地址!");
                        else
                       MessageBox.Show("Communication error, please check the address!");
                        
                        m_Runing = false;
                        button3.Enabled = true;
                        return;

                    }

                }
                else
                {
         
                    if (strLang == "ChineseSimplified")
                        MessageBox.Show("串口未打开", "提示");
                    else
                        MessageBox.Show("Serial port is not opene", "Tips");
                    m_Runing = false;
                    button3.Enabled = true;
                    return;
                }


                if (!m_Runing)
                {
                    if (strLang == "ChineseSimplified")
                    button3.Text = "停止测试";
                    else
                    button3.Text = "Stop test";
                    m_Runing = true;
                    listView1.Items.Clear();
                    dataGridView3.Rows.Clear();
                    dataGridView4.Rows.Clear();
                    button41.Enabled = true;//实时数据正在读取，可以暂停
                    thread_poll = new Thread(new ThreadStart(Poll_Thread));
                    thread_poll.Start();
                }
                else
                {
                    if (strLang == "ChineseSimplified")
                        button3.Text = "开始测试";
                    else
                        button3.Text = "Start test";
                button41.Enabled = false;//实时数据正在读取
                m_Runing = false;
                }
                button3.Enabled = true;
        }

        private void ShowBatModuleAddr()
        {
            ushort[] registerhold = new ushort[2];
            bool bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 2306, 1, ref registerhold);//电池节数
            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            if (bhold)
            {
                textBox24.Text = registerhold[0].ToString();
            }
            else
            {
                if (strLang == "ChineseSimplified")
                MessageBox.Show("获取数据失败!", "提示");
                else
                    MessageBox.Show("Failed to get data!", "TIPS", MessageBoxButtons.OK);
            }
        }
        string  GetIntToWeek(ushort value)
        {
            string strValue = "";
            if (value == 0)
            {
                strValue = "星期日";
            }
            if (value == 1)
            {
                strValue = "星期一";
            }
            if (value == 2)
            {
                strValue = "星期二";
            }
            if (value == 3)
            {
                strValue = "星期三";
            }
            if (value == 4)
            {
                strValue = "星期四";
            }
            if (value == 5)
            {
                strValue = "星期五";
            }
            if (value == 6)
            {
                strValue = "星期六";
            }
            return strValue;
        }
        string GetIntToWeek2(ushort value)
        {
            string strValue = "";
            if (value == 0)
            {
                strValue = "Sunday";
            }
            if (value == 1)
            {
                strValue = "Monday";
            }
            if (value == 2)
            {
                strValue = "Tuesday";
            }
            if (value == 3)
            {
                strValue = "Wednesday";
            }
            if (value == 4)
            {
                strValue = "Thursday";
            }
            if (value == 5)
            {
                strValue = "Friday";
            }
            if (value == 6)
            {
                strValue = "Saturday";
            }
            return strValue;
        }
        private string GetWeekFromEnToChName2(DayOfWeek week)
        {
            string name = "";
            switch (week)
            {
                case DayOfWeek.Monday:
                    name = "Monday";
                    break;
                case DayOfWeek.Tuesday:
                    name = "Tuesday";
                    break;
                case DayOfWeek.Wednesday:
                    name = "Wednesday";
                    break;
                case DayOfWeek.Thursday:
                    name = "Thursday";
                    break;
                case DayOfWeek.Friday:
                    name = "Friday";
                    break;
                case DayOfWeek.Saturday:
                    name = "Saturday";
                    break;
                case DayOfWeek.Sunday:
                    name = "Sunday";
                    break;
            }
            return name;
        }
        void GetDeviceAndSververTime(string devTime, string localTime)
        {

            textBox26.Text = devTime;

            textBox27.Text = localTime;
            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            if (strLang == "ChineseSimplified")
            label39.Text = "获取结束";
            else
            label39.Text = "Read complete";

            button11.Enabled = true;
            button12.Enabled = true;

            button10.Enabled = true;
            button9.Enabled = true;
        }
        private void Poll_Thread2()
        {

            ushort[] registerhold = new ushort[7];
            bool bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 2100, 7, ref registerhold);//
            string Value = "";
            string Value2 = "";
            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            if (bhold)
            {

                if (strLang == "ChineseSimplified")
                    Value = registerhold[0] + "年" + registerhold[1].ToString("00") + "月" + registerhold[2].ToString("00") + " " + GetIntToWeek(registerhold[3]) + " " + registerhold[4].ToString("00") + "时" + registerhold[5].ToString("00") + "分" + registerhold[6] + "秒 ";
                else
                {
                    //April 9, 2022 Saturday 11:58:18

                    Value = GetEnMonth(registerhold[1].ToString()) + " " + registerhold[2].ToString() + "," + registerhold[0].ToString() + " " + GetIntToWeek2(registerhold[3]) + " " + registerhold[4].ToString("00") + ":" + registerhold[5].ToString("00") + ":" + registerhold[6];
                }
             
                //textBox26.Text = Value;
            }
            else
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("获取数据失败!", "提示");
                else
                    MessageBox.Show("Failed to get data!", "TIPS", MessageBoxButtons.OK);
                return;
                //Value = "通信失败!";
            }
            string current = GetBeijingTime();
            if (current == "") GetBeijingTime();
            if (current == "")
            {
                DateTime time = DateTime.Now.ToLocalTime();
                string weekname = GetWeekFromEnToChName(time.DayOfWeek);
                //Value2 = time.Year + "年" + time.Month + "月" + time.Day + " " + weekname + " " + time.Hour + "时" + time.Minute + "分" + time.Second + "秒 ";

                if (strLang == "ChineseSimplified")
                    Value2 = time.Year + "年" + time.Month + "月" + time.Day + " " + weekname + " " + time.Hour + "时" + time.Minute + "分" + time.Second + "秒 ";
                else
                {
                    //April 9, 2022 Saturday 11:58:18
                    weekname = GetWeekFromEnToChName2(time.DayOfWeek);
                    Value2 = GetEnMonth(time.Month.ToString()) + " " + time.Day.ToString() + "," + time.Year.ToString() + " " + weekname + " " + time.Hour + ":" + time.Minute + ":" + time.Second;
                }
                //textBox27.Text = Value;
            }
            else
            {
                //DateTime time = Convert.ToDateTime(current).ToString("yyyy-MM-dd HH:mm:ss");
                if (strLang == "ChineseSimplified")
                    Value2 = Convert.ToDateTime(current).ToString("yyyy年MM月dd dddd HH时mm分ss秒");
                else
                {
                    DateTime time = Convert.ToDateTime(current);
                    string weekname = GetWeekFromEnToChName2(time.DayOfWeek);
                    Value2 = GetEnMonth(time.Month.ToString()) + " " + time.Day.ToString() + "," + time.Year.ToString() + " " + weekname + " " + time.Hour + ":" + time.Minute + ":" + time.Second;
                }
            }
            Invoke(new ShowTimeInfo(GetDeviceAndSververTime), new object[] {Value, Value2});
        }
        private void GetParamTestValue()
        {
            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            
            if (!m_isPortOpen)
            {
                if (strLang == "ChineseSimplified")
                MessageBox.Show("串口未打开");
                else
                MessageBox.Show("Serial port is not opened");
                return;
            }
            textBox5.Text = "";
            textBox6.Text = "";
            textBox7.Text = "";

            textBox10.Text = "";
            textBox9.Text = "";
            textBox8.Text = "";

            textBox13.Text = "";
            textBox12.Text = "";
            textBox11.Text = "";

            textBox16.Text = "";
            textBox15.Text = "";
            textBox14.Text = "";


            textBox19.Text = "";
            textBox18.Text = "";
            textBox17.Text = "";

            textBox21.Text = "";
            textBox20.Text = "";

            textBox22.Text = "";

            float value = 0;
            ushort[] registerhold = new ushort[50];
            bool bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 2001, 38, ref registerhold);//电池节数
            if (bhold)
            {
                textBox5.Text = registerhold[3].ToString();
                textBox6.Text = registerhold[4].ToString();
                textBox7.Text = registerhold[5].ToString();

                textBox10.Text = registerhold[6].ToString();

                value = (float)(registerhold[7]) / 1000;
                textBox9.Text = value.ToString();

                value = (float)(registerhold[8]) / 1000;
                textBox8.Text = value.ToString();

                value = (float)(registerhold[9]) / 10;
                textBox13.Text = value.ToString();

                value = (float)(registerhold[10]) / 10;
                textBox12.Text = value.ToString();
                
                
                textBox11.Text = registerhold[11].ToString();

                textBox16.Text = registerhold[12].ToString();
                textBox15.Text = registerhold[13].ToString();

                textBox70.Text = registerhold[14].ToString();


                textBox14.Text = registerhold[15].ToString();

                textBox71.Text = registerhold[16].ToString();
                textBox72.Text = registerhold[17].ToString();



                textBox19.Text = registerhold[18].ToString();
                textBox18.Text = registerhold[19].ToString();
                textBox17.Text = registerhold[20].ToString();

                textBox21.Text = registerhold[21].ToString();
                textBox20.Text = registerhold[22].ToString();
                textBox22.Text = registerhold[0].ToString();


                //////////////////////新增加
                textBox65.Text = registerhold[23].ToString();
                textBox64.Text = registerhold[24].ToString();

              
                value = (float)(registerhold[25]) / 1000;
                textBox63.Text = value.ToString("0.000");

                value = (float)(registerhold[26]) / 1000;
                textBox62.Text = value.ToString("0.000");


                value = (float)(registerhold[27]) / 10;
                textBox61.Text = value.ToString("0.0");


                value = (float)(registerhold[28]) / 10;
                textBox60.Text = value.ToString("0.0");

                textBox59.Text = registerhold[29].ToString();//7

                value = (float)(registerhold[30]) / 1000;
                textBox58.Text = value.ToString("0.000");

                value = (float)(registerhold[31]) / 1000;
                textBox57.Text = value.ToString("0.000");

                value = (float)(registerhold[32]) / 1000;
                textBox56.Text = value.ToString("0.000");

                value = (float)(registerhold[33]) / 1000;
                textBox55.Text = value.ToString("0.000");

                value = (float)(registerhold[34]) / 1000;
                textBox54.Text = value.ToString("0.000");

                value = (float)(registerhold[35]) / 1000;
                textBox53.Text = value.ToString("0.000");

                value = (float)(registerhold[36]) / 1000;
                textBox52.Text = value.ToString("0.000");

                value = (float)(registerhold[37]) / 1000;
                textBox51.Text = value.ToString("0.000");

                ////////////////////////////////
                bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 2080, 9, ref registerhold);//电池额定容量

                textBox66.Text = registerhold[0].ToString();
                textBox67.Text = registerhold[1].ToString();
                textBox68.Text = registerhold[2].ToString();
                textBox69.Text = registerhold[3].ToString();
                
                textBox38.Text = registerhold[4].ToString();

                value = (float)(registerhold[5]) / 1000;
                textBox39.Text = value.ToString("0.000");

                value = (float)(registerhold[6]) / 1000;
                textBox40.Text = value.ToString("0.000");

                value = (float)(registerhold[7]) / 1000;
                textBox41.Text = value.ToString("0.000");

                value = (float)(registerhold[8]) / 1000;
                textBox42.Text = value.ToString("0.000");

            }
            else
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("获取数据失败!", "提示");
                else
                    MessageBox.Show("Failed to get data!", "TIPS", MessageBoxButtons.OK);
            }
             //ushort[] registerhold = new ushort[120];
            bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 2089, 1, ref registerhold);//电池节数
            if (bhold)
            {
                textBox23.Text = registerhold[0].ToString();
            }
            /////////////////读取波特率和校验位
            bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 2092, 2, ref registerhold);//电池额定容量
            if (bhold)
            {
                comboBox7.SelectedIndex = registerhold[0] - 1;
                comboBox8.SelectedIndex = registerhold[1];
            }
            else
            {
                comboBox7.Text = "";
                comboBox8.Text = "";
            }

        }
        private void GetSysConfValue()
        {
            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();

            if (!m_isPortOpen)
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("串口未打开");
                else
                    MessageBox.Show("Serial port is not opened");
                return;
            }
           
            textBox22.Text = "";

      
            ushort[] registerhold = new ushort[50];
            bool bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 2001, 1, ref registerhold);//电池节数
            if (bhold)
            {               
                textBox22.Text = registerhold[0].ToString();    
            }
            else
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("获取数据失败!", "提示");
                else
                    MessageBox.Show("Failed to get data!", "TIPS");
            }
            //ushort[] registerhold = new ushort[120];
            bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 2089, 1, ref registerhold);//电池节数
            if (bhold)
            {
                textBox23.Text = registerhold[0].ToString();
            }
            /////////////////读取波特率和校验位
            bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 2092, 2, ref registerhold);//电池额定容量
            if (bhold)
            {
                comboBox7.SelectedIndex = registerhold[0] - 1;
                comboBox8.SelectedIndex = registerhold[1];
            }
            else
            {
                comboBox7.Text = "";
                comboBox8.Text = "";
            }
            ////////////////////////////////
            bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 2039, 4, ref registerhold);//
            if (bhold)
            {
                GetShinengStatus(3, 1, registerhold[0]);
                GetShinengStatus(7, 1, registerhold[1]);
                GetShinengStatus(11, 1, registerhold[2]);
                GetShinengStatus(15, 1, registerhold[3]);
            }
            ////////////////////////////////
            bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 2043, 18, ref registerhold);// 充放电类型、电池组号
            if (bhold)
            {
                for (int i = 0; i < 18; i++)
                {
                    if (i == 1) continue;
                    GetSeniorAndGroupStatus(i, registerhold[i]);
                }
            }
            ////////////////////量程
            bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 2061, 18, ref registerhold);// 充放电类型、电池组号
            if (bhold)
            {
                for (int i = 0; i < 18; i++)
                {
                    if (i == 1) continue;
                    GetSystemRangeStatus(i, registerhold[i]);
                }
            }
        }
        private string GetEnMonth(string strMonth)
        {
            string strENMonth = "";
            if (strMonth == "1")
            {
                strENMonth = "January";
            }
            else if (strMonth == "2")
            {
                strENMonth = "February ";
            }
            else if (strMonth == "3")
            {
                strENMonth = "March";
            }
            else if (strMonth == "4")
            {
                strENMonth = "April";
            }
            else if (strMonth == "5")
            {
                strENMonth = "May";
            }
            else if (strMonth == "6")
            {
                strENMonth = "June";
            }
            else if (strMonth == "7")
            {
                strENMonth = "July";
            }
            else if (strMonth == "8")
            {
                strENMonth = "August";
            }
            else if (strMonth == "9")
            {
                strENMonth = "September";
            }
            else if (strMonth == "10")
            {
                strENMonth = "October";
            }
            else if (strMonth == "11")
            {
                strENMonth = "November";
            }
            else if (strMonth == "12")
            {
                strENMonth = "December";
            }
            return strENMonth;
        }
        private void Poll_Thread()
        {
           // byte SlaveAddr = 1;
            //ushort naddr = 0;
            ushort[] registerhold = new ushort[8];
            string sVoltValue = "111";
            string sTempValue = "222";
            string sNeizuValue = "333";
            ushort value = 0x01;
            //ushort value2 = 0x08;
            //ushort value3 = 0;
            float value4 = 0;
            string strTotalVol = "";
            string strTotalCur = "";
            string strTemp1 = "";
            string strTemp2 = "";
            string strcount = "";
            string strVersion = "";
            string strTotalcap= "";
            string strTotaldistime = "";
            string strCapacity = "";
            string strCapacity2 = "";

            string strAvgVolt = "";
            string strAvgTemp = "";
            string strAvgNeizu = "";

            string strChCurStus = "";
            string strNeiZuTestStus = "";
            string strNeiZuUpdateTime = "";

            ushort icount = 0;
            ushort[] registerhold2 = new ushort[120];
            ushort[] registerhold3 = new ushort[120];
            ushort[] registerhold4 = new ushort[120];
            int value5 = 0;
            //byte tempvalue=0;
            while (m_Runing)
            {
                /////////////////////读总的信息
                if (m_SelectIndex == 0)
                {

                    if (!m_Runing) return;
                    
                    bool bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 2001, 1, ref registerhold);//电池节数
                    if (bhold)
                    {
                        value = registerhold[0];
                        icount = value;
                        strcount = value.ToString();
                        label_14_count.Text = icount.ToString();
                        label_countTemp.Text = icount.ToString();
                    }

                    bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 2000, 1, ref registerhold);//版本
                    if (bhold)
                    {
                        value = registerhold[0];

                        strVersion = value.ToString();
                    }

                    Language lang = this.CurrentSelectedLanguage;
                    string strLang = lang.ToString();
                    //////////////////////////////获取时间

                    if (!m_Runing) return;
               
                    bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 2100, 7, ref registerhold);//
                    string DeviceTime = "";
            
                    if (bhold)
                    {

                        if (strLang == "ChineseSimplified")
                            DeviceTime = registerhold[0].ToString() + "年" + registerhold[1].ToString("00") + "月" + registerhold[2].ToString("00") + " " + GetIntToWeek(registerhold[3]) + " " + registerhold[4].ToString("00") + "时" + registerhold[5].ToString("00") + "分" + registerhold[6] + "秒 ";
                        else
                        {
                             //April 9, 2022 Saturday 11:58:18

                            DeviceTime = GetEnMonth(registerhold[1].ToString()) + " " + registerhold[2].ToString() + "," + registerhold[0].ToString() + " " + GetIntToWeek2(registerhold[3]) + " " + registerhold[4].ToString("00") + ":" + registerhold[5].ToString("00") + ":" + registerhold[6];
                        }
                        //textBox26.Text = Value;
                    }
                    else
                    {
                        if (strLang == "ChineseSimplified")
                            DeviceTime = "Failed to get time!";
                        else
                            DeviceTime = "获取时间失败!";
                        //Value = "通信失败!";
                    }
                    if (!m_Runing) return;
                    ///////////////////////////////
                    bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 1, 4, ref registerhold);//总电压、电流、温度
                    if (bhold)
                    {
                        //sVoltValue = registerhold[0]
                        value = registerhold[0];
                        value4 = (float)(value) / 10;
                        strTotalVol = value4.ToString();

                        value = registerhold[1];
                        if (value > 32767)
                        {
                            value5 = (value - 65536);
                            value4 = (float)(value5) / 10;
                        }
                        else
                        {
                            value4 = (float)(value) / 10;
                        }
                        strTotalCur = value4.ToString();

                        value = registerhold[2];
                        if (value > 32767)
                        {
                            value5 = (value - 65536);
                            value4 = (float)(value5) / 10;
                        }
                        else
                        {
                            value4 = (float)(value) / 10;
                        }
                        strTemp1 = value4.ToString();

                        value = registerhold[3];
                        if (value > 32767)
                        {
                            value5 = (value - 65536);
                            value4 = (float)(value5) / 10;
                        }
                        else
                        {
                            value4 = (float)(value) / 10;
                        }
                        strTemp2 = value4.ToString();
                        ///////////////////// 增加对电池阻容量、电池放电时间
                        bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 11, 3, ref registerhold);//电池容量、电池放电时间
                        value = registerhold[0];

                        if (isShowCapacity)
                            strTotalcap = value.ToString();
                        else
                            strTotalcap = "";

                        value = registerhold[2];
                        value4 = (float)(value) / 10;
                        strCapacity2 = value4.ToString("0.0");

                        /////////平均电压,平均温度,平均内阻
                        bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 5, 3, ref registerhold);
                        value = registerhold[0];
                        value4 = (float)(value) / 1000;
                        strAvgVolt = value4.ToString("0.000");

                        value = registerhold[1];
                        value4 = (float)(value) / 10;
                        strAvgTemp = value4.ToString("0.0");

                        value = registerhold[2];
                        value4 = (float)(value) / 1000;
                        strAvgNeizu = value4.ToString("0.000");


                        //string strChCurStus = "";
                        //string strNeiZuTestStus = "";
                        //string strNeiZuUpdateTime = "";
                        /////////电池电流状态
                        bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 14, 1, ref registerhold);
                        value = registerhold[0];
                        if (strLang == "ChineseSimplified")
                        {
                            if (value == 0)
                                strChCurStus = "浮充";
                            else if (value == 1)
                                strChCurStus = "放电";
                            else if (value == 2)
                                strChCurStus = "均充";
                            else
                                strChCurStus = "离线";
                        }
                        else
                        {
                            if (value == 0)
                                strChCurStus = "F-charge";
                            else if (value == 1)
                                strChCurStus = "Discharge";
                            else if (value == 2)
                                strChCurStus = "E-charge";
                            else
                                strChCurStus = "off-line";
                        }
                        /////////////

                        
                        /////////内阻测量状态
                        bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 21, 1, ref registerhold);
                        value = registerhold[0];

                       
                        if (strLang == "ChineseSimplified")
                        {
                            if (value == 0)
                                strNeiZuTestStus = "当前未进行内阻测试";
                            else if (value == 1)
                                strNeiZuTestStus = "正在进行内阻测试";

                            //strNeiZuUpdateTime = registerhold[0].ToString() + "年" + registerhold[1].ToString() + "月" + registerhold[2].ToString() + "日 " + registerhold[3].ToString() + ":" + registerhold[4].ToString();
                        }
                        else
                        {
                            if (value == 0)
                                strNeiZuTestStus = "RES test is not start";
                            else if (value == 1)
                                strNeiZuTestStus = "RES test is in progress";
                         
                            //strNeiZuUpdateTime = registerhold[0].ToString() + "年" + registerhold[1].ToString() + "月" + registerhold[2].ToString() + "日 " + registerhold[3].ToString() + ":" + registerhold[4].ToString();
                           // strNeiZuUpdateTime = GetEnMonth(registerhold[1].ToString()) + " " + registerhold[2].ToString() + "," + registerhold[0].ToString() + registerhold[3].ToString() + ":" + registerhold[4].ToString();
                        }
                       
                        /////////内阻更新时间
                        bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 22, 5, ref registerhold);

                        if (strLang == "ChineseSimplified")
                        {
                           
                            strNeiZuUpdateTime = registerhold[0].ToString() + "年" + registerhold[1].ToString() + "月" + registerhold[2].ToString() + "日 " + registerhold[3].ToString() + ":" + registerhold[4].ToString();
                        }
                        else
                        {
                           
                            //strNeiZuUpdateTime = registerhold[0].ToString() + "年" + registerhold[1].ToString() + "月" + registerhold[2].ToString() + "日 " + registerhold[3].ToString() + ":" + registerhold[4].ToString();
                            strNeiZuUpdateTime = GetEnMonth(registerhold[1].ToString()) + " " + registerhold[2].ToString() + "," + registerhold[0].ToString() + " "+ registerhold[3].ToString() + ":" + registerhold[4].ToString();
                        }

                        
                        Invoke(new ShowTestInfo(ShowTestInfoToUser), new object[] { strTotalVol, strTotalCur, strTemp1, strTemp2, strcount, strVersion, DeviceTime, strTotalcap, strCapacity2,strAvgVolt, strAvgTemp, strAvgNeizu,strChCurStus, strNeiZuTestStus, strNeiZuUpdateTime });
                    }
                    else
                    {
                        Invoke(new ShowTestInfo(ShowTestInfoToUser), new object[] { strTotalVol, strTotalCur, strTemp1, strTemp2, strcount, "通信错误!", DeviceTime, strTotalcap, strCapacity2,strAvgVolt, strAvgTemp, strAvgNeizu, strChCurStus, strNeiZuTestStus, strNeiZuUpdateTime });
                        //m_Runing = false;
                        //MessageBox.Show("通信断开,请重新点击开始");
                        //return;
                        Thread.Sleep(1000);
                        if (!m_Runing) return;
                        continue;
                    }

                    /////////////////////
                    ////////////////////
                    if (!m_Runing) return;
                    //icount = 2;
                    Invoke(new ConfirmListCount(ConfirmDeleteList), new object[] { (byte)(icount) });
                    Thread.Sleep(20);
                    //if (listView1.Items.Count == 0)
                    {

                        if (icount <= 40)
                        {
                            bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 50, (ushort)(3 * icount), ref registerhold2);
                            bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 7005, (ushort)(1 * icount), ref registerhold3);
                            bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 7205, (ushort)(1 * icount), ref registerhold4);
                            if (bhold)
                            {
                                for (byte i = 0; i < icount; i++)
                                {

                                    if (!m_Runing) return;
                                    value = registerhold2[3 * i];
                                    value4 = (float)(value) / 1000;
                                    sVoltValue = value4.ToString();

                                    value = registerhold2[3 * i + 1];
                                    if (value > 32767)
                                    {
                                        value5 = (value - 65536);
                                        value4 = (float)(value5) / 10;
                                    }
                                    else
                                    {
                                        value4 = (float)(value) / 10;
                                    }
                                    sTempValue = value4.ToString();

                                    value = registerhold2[3 * i + 2];
                                    value4 = (float)(value) / 1000;
                                    sNeizuValue = value4.ToString();

                                    ////////////////////
                                 
                                    value = registerhold3[i];
                                    strCapacity = value.ToString();

                                    value = registerhold4[i];
                                    value4 = (float)(value) / 10;
                                    strCapacity2 = value4.ToString("0.0");

                                    if (!isShowCapacity)
                                    {
                                        strCapacity = "";
                                        strCapacity2 = "";
                                    }
                                    //////////////////////
                                    Invoke(new InsertTestRecordToList(InsertTestResult), new object[] { sVoltValue, sTempValue, sNeizuValue, i, strCapacity, strCapacity2});
                                    Invoke(new SetResistanceDelegate(setResistance), new object[] { sNeizuValue, i });
                                    Invoke(new SetResistanceDelegate(setTemplate), new object[] { sTempValue, i });
                                }
                            }
                        }
                        else if (icount > 40 && icount <= 80)
                        {
                            bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 50, 120, ref registerhold2);
                            bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 7005, 40, ref registerhold3);
                            bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 7205, 40, ref registerhold4);
                            if (bhold)
                            {
                                for (byte i = 0; i < 40; i++)
                                {
                                    //if(i==
                                    if (!m_Runing) return;
                                    value = registerhold2[3 * i];
                                    value4 = (float)(value) / 1000;
                                    sVoltValue = value4.ToString();

                                    value = registerhold2[3 * i + 1];
                                    if (value > 32767)
                                    {
                                        value5 = (value - 65536);
                                        value4 = (float)(value5) / 10;
                                    }
                                    else
                                    {
                                        value4 = (float)(value) / 10;
                                    }
                                    sTempValue = value4.ToString();

                                    value = registerhold2[3 * i + 2];
                                    value4 = (float)(value) / 1000;
                                    sNeizuValue = value4.ToString();

                                    /////////////////////////////
                                    value = registerhold3[i];
                                    strCapacity = value.ToString();

                                    value = registerhold4[i];
                                    value4 = (float)(value) / 10;
                                    strCapacity2 = value4.ToString("0.0");
                                    if (!isShowCapacity)
                                    {
                                        strCapacity = "";
                                        strCapacity2 = "";
                                    }
                                    ///////////////////////////////
                                    Invoke(new InsertTestRecordToList(InsertTestResult), new object[] { sVoltValue, sTempValue, sNeizuValue, i, strCapacity, strCapacity2 });
                                    Invoke(new SetResistanceDelegate(setResistance), new object[] { sNeizuValue, i });
                                    Invoke(new SetResistanceDelegate(setTemplate), new object[] { sTempValue, i });
                                }
                            }
                            bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 170, (ushort)((icount - 40) * 3), ref registerhold2);
                            bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 7045, (ushort)(icount - 40), ref registerhold3);
                            bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 7245, (ushort)(icount - 40), ref registerhold4);
                            if (bhold)
                            {
                                for (byte i = 0; i < icount-40; i++)
                                {
                                    if (!m_Runing) return;
                                    value = registerhold2[3 * i];
                                    value4 = (float)(value) / 1000;
                                    sVoltValue = value4.ToString();

                                    value = registerhold2[3 * i + 1];
                                    if (value > 32767)
                                    {
                                        value5 = (value - 65536);
                                        value4 = (float)(value5) / 10;
                                    }
                                    else
                                    {
                                        value4 = (float)(value) / 10;
                                    }
                                    sTempValue = value4.ToString();

                                    value = registerhold2[3 * i + 2];
                                    value4 = (float)(value) / 1000;
                                    sNeizuValue = value4.ToString();
                                    /////////////////////////////
                                    value = registerhold3[i];
                                    strCapacity = value.ToString();

                                    value = registerhold4[i];
                                    value4 = (float)(value) / 10;
                                    strCapacity2 = value4.ToString("0.0");
                                    if (!isShowCapacity)
                                    {
                                        strCapacity = "";
                                        strCapacity2 = "";
                                    }
                                    ///////////////////////////////

                                    Invoke(new InsertTestRecordToList(InsertTestResult), new object[] { sVoltValue, sTempValue, sNeizuValue, (byte)(40 + i), strCapacity, strCapacity2 });
                                    Invoke(new SetResistanceDelegate(setResistance), new object[] { sNeizuValue, (byte)(40 + i) });
                                    Invoke(new SetResistanceDelegate(setTemplate), new object[] { sTempValue, (byte)(40 + i) });
                                }
                            }

                        }
                        else if (icount > 80)
                        {
                            bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 50, 120, ref registerhold2);
                            bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 7005, 40, ref registerhold3);
                            bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 7205, 40, ref registerhold4);
                            if (bhold)
                            {
                                for (byte i = 0; i < 40; i++)
                                {
                                    if (!m_Runing) return;
                                    value = registerhold2[3 * i];
                                    value4 = (float)(value) / 1000;
                                    sVoltValue = value4.ToString();

                                    value = registerhold2[3 * i + 1];
                                    if (value > 32767)
                                    {
                                        value5 = (value - 65536);
                                        value4 = (float)(value5) / 10;
                                    }
                                    else
                                    {
                                        value4 = (float)(value) / 10;
                                    }
                                    sTempValue = value4.ToString();

                                    value = registerhold2[3 * i + 2];
                                    value4 = (float)(value) / 1000;
                                    sNeizuValue = value4.ToString();

                                    /////////////////////////////
                                    value = registerhold3[i];
                                    strCapacity = value.ToString();
                                    ///////////
                                    value = registerhold4[i];
                                    value4 = (float)(value) / 10;
                                    strCapacity2 = value4.ToString("0.0");
                                    if (!isShowCapacity)
                                    {
                                        strCapacity = "";
                                        strCapacity2 = "";
                                    }
                                    ///////////////////////////////

                                    Invoke(new InsertTestRecordToList(InsertTestResult), new object[] { sVoltValue, sTempValue, sNeizuValue, i, strCapacity, strCapacity2 });
                                    Invoke(new SetResistanceDelegate(setResistance), new object[] { sNeizuValue, i });
                                    Invoke(new SetResistanceDelegate(setTemplate), new object[] { sTempValue, i });
                                }
                            }
                            bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 170, 120, ref registerhold2);
                            bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 7045, 40, ref registerhold3);
                            bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 7245, 40, ref registerhold4);
                            if (bhold)
                            {
                                for (byte i = 0; i < 40; i++)
                                {
                                    if (!m_Runing) return;
                                    value = registerhold2[3 * i];
                                    value4 = (float)(value) / 1000;
                                    sVoltValue = value4.ToString();

                                    value = registerhold2[3 * i + 1];
                                    if (value > 32767)
                                    {
                                        value5 = (value - 65536);
                                        value4 = (float)(value5) / 10;
                                    }
                                    else
                                    {
                                        value4 = (float)(value) / 10;
                                    }
                                    sTempValue = value4.ToString();

                                    value = registerhold2[3 * i + 2];
                                    value4 = (float)(value) / 1000;
                                    sNeizuValue = value4.ToString();

                                    /////////////////////////////
                                    value = registerhold3[i];
                                    strCapacity = value.ToString();
                                    ///////////
                                    value = registerhold4[i];
                                    value4 = (float)(value) / 10;
                                    strCapacity2 = value4.ToString("0.0");
                                    if (!isShowCapacity)
                                    {
                                        strCapacity = "";
                                        strCapacity2 = "";
                                    }
                                    Invoke(new InsertTestRecordToList(InsertTestResult), new object[] { sVoltValue, sTempValue, sNeizuValue, (byte)(40 + i), strCapacity, strCapacity2 });
                                    Invoke(new SetResistanceDelegate(setResistance), new object[] { sNeizuValue, (byte)(40 + i) });
                                    Invoke(new SetResistanceDelegate(setTemplate), new object[] { sTempValue, (byte)(40 + i) });
                                }
                            }
                            bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 290, (ushort)((icount - 80) * 3), ref registerhold2);
                            bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 7085, (ushort)(icount - 80), ref registerhold3);
                            bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 7285, (ushort)(icount - 80), ref registerhold4);
                            if (bhold)
                            {
                                for (byte i = 0; i < icount-80; i++)
                                {

                                    if (!m_Runing) return;
                                    value = registerhold2[3 * i];
                                    value4 = (float)(value) / 1000;
                                    sVoltValue = value4.ToString();

                                    value = registerhold2[3 * i + 1];
                                    if (value > 32767)
                                    {
                                        value5 = (value - 65536);
                                        value4 = (float)(value5) / 10;
                                    }
                                    else
                                    {
                                        value4 = (float)(value) / 10;
                                    }
                                    sTempValue = value4.ToString();

                                    value = registerhold2[3 * i + 2];
                                    value4 = (float)(value) / 1000;
                                    sNeizuValue = value4.ToString();

                                    /////////////////////////////
                                    value = registerhold3[i];
                                    strCapacity = value.ToString();
                                    ///////////
                                    value = registerhold4[i];
                                    value4 = (float)(value) / 10;
                                    strCapacity2 = value4.ToString("0.0");
                                    if (!isShowCapacity)
                                    {
                                        strCapacity = "";
                                        strCapacity2 = "";
                                    }

                                    Invoke(new InsertTestRecordToList(InsertTestResult), new object[] { sVoltValue, sTempValue, sNeizuValue, (byte)(80 + i), strCapacity, strCapacity2 });
                                    Invoke(new SetResistanceDelegate(setResistance), new object[] { sNeizuValue, (byte)(80 + i) });
                                    Invoke(new SetResistanceDelegate(setTemplate), new object[] { sTempValue, (byte)(80 + i) });
                                }
                            }
                        }

                    }

                }
                else if (m_SelectIndex == 1)
                {

                    // GetParamTestValue();

                }



                Thread.Sleep(1000);
                //////////////////


            }
           

             //   
            //}

        }

        private void ShowTestInfoToUser(string volt, string curr, string temp1, string temp2, string count, string version, string strDeviceTime, string strCapacity, string strDisTime, string strAvgVolt, string strAvgTemp, string strAvgNeizu, string strChCurStus, string strNeiZuTestStus, string strNeiZuUpdateTime)
        {
            textBox1.Text = curr;
            textBox2.Text = volt;
            textBox3.Text = temp1;
            textBox4.Text = temp2;
            label18.Text = count;
            label15.Text = strDeviceTime;
            textBox37.Text = strCapacity;
            textBox28.Text = strDisTime;

            textBox45.Text = strAvgVolt;
            textBox43.Text = strAvgTemp;
            textBox48.Text = strAvgNeizu;

            label76.Text = strChCurStus;
            label77.Text = strNeiZuTestStus;
            label78.Text = strNeiZuUpdateTime;

            int pos = version.IndexOf("错误");
            if (pos >= 0)
            {
                label19.ForeColor = Color.Red;
                label15.ForeColor = Color.Red;
                //m_bStart = false;
                //button3.Enabled = true;
                //button3.Text = "开始检测";
                
            }
            else
            {
                label19.ForeColor = Color.Blue;
                label15.ForeColor = Color.Blue;
                //button3.Enabled = false;
               // button3.Text = "停止检测";
            }
            label19.Text = version;
            //listView1.Items.Clear();
           
        }
        private void InsertTestResult(string volt, string temp, string neizu, byte index, string capacity, string capacity2)
        {

            if (listView1.Items.Count < index + 1)
            {

                ListViewItem OptionItem = new ListViewItem((index + 1).ToString());

                OptionItem.UseItemStyleForSubItems = false;
                OptionItem.SubItems.Add(volt);//
                OptionItem.SubItems.Add(temp);//
                OptionItem.SubItems.Add(neizu);//
                OptionItem.SubItems.Add(capacity);//
                OptionItem.SubItems.Add(capacity2);//
                listView1.Items.Add(OptionItem);//执行添加操作
            }
            else
            {
                listView1.Items[index].SubItems[1].Text = volt;
                listView1.Items[index].SubItems[2].Text = temp;
                listView1.Items[index].SubItems[3].Text = neizu;
                listView1.Items[index].SubItems[4].Text = capacity;
                listView1.Items[index].SubItems[5].Text = capacity2;
            }
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {

            try
            {
                Language lang = this.CurrentSelectedLanguage;
                string strLang = lang.ToString();

                if (tabControl1.SelectedTab.Name == "tabPage1")
                {
                    //MessageBox.Show("实时数据");
                    m_SelectIndex = 0;
                    if (!m_isPortOpen)
                    {
                        if (strLang == "ChineseSimplified")
                        {
                            MessageBox.Show("串口未打开", "提示");
                        }
                        else
                        {
                            MessageBox.Show("Port is not open", "Tips");
                        }
                        return;
                    }

                }
                else if (tabControl1.SelectedTab.Name == "tabPage2")
                {
                    //MessageBox.Show("参数设置");
                    //tabControl1.SelectedIndex = 0;
                    m_SelectIndex = 1;
                    if (m_isPortOpen)
                    {
                        GetParamTestValue();
                    }
                    else
                    {
                        if (strLang == "ChineseSimplified")
                        {
                            MessageBox.Show("串口未打开", "提示");
                        }
                        else
                        {
                            MessageBox.Show("Port is not open", "Tips");
                        }
                        return;
                    }
                }
                else if (tabControl1.SelectedTab.Name == "tabPage3")
                {
                    //MessageBox.Show("参数设置");
                    //tabControl1.SelectedIndex = 0;
                    m_SelectIndex = 2;
                    if (m_isPortOpen)
                    {
                        ShowBatModuleAddr();
                    }
                    else
                    {
                        if (strLang == "ChineseSimplified")
                        {
                            MessageBox.Show("串口未打开", "提示");
                        }
                        else
                        {
                            MessageBox.Show("Port is not open", "Tips");
                        }
                        return;
                    }
                }
                else if (tabControl1.SelectedTab.Name == "tabPage4")
                {
                    //MessageBox.Show("参数设置");
                    m_SelectIndex = 3;
                    //tabControl1.SelectedIndex = 0;
                    button11.Enabled = false;
                    button12.Enabled = false;
                    button10.Enabled = false;
                    button9.Enabled = false;
                    if (m_isPortOpen)
                    {
                        GetDeviceTestModeInfo();
                        if (strLang == "ChineseSimplified")
                        {
                            label39.Text = "正在获取时间...";
                        }
                        else
                        {
                            label39.Text = "it is getting time now...";
                        }
                        textBox26.Text = "";

                        textBox27.Text = "";
                        thread_poll2 = new Thread(new ThreadStart(Poll_Thread2));
                        thread_poll2.Start();
                    }
                    else
                    {

                        if (strLang == "ChineseSimplified")
                        {
                            MessageBox.Show("串口未打开", "提示");
                        }
                        else
                        {
                            MessageBox.Show("Port is not open", "Tips");
                        }
                        return;

                    }


                    //GetDeviceAndSververTime(); 
                }
                else if (tabControl1.SelectedTab.Name == "tabPage12")//系统参数
                {
                    //MessageBox.Show("参数设置");
                    //tabControl1.SelectedIndex = 0;
                    //return;
                    this.Update();
                    tabControl1.Update();
                    if (!m_isPortOpen)
                    {
                        if (strLang == "ChineseSimplified")
                        {
                            MessageBox.Show("串口未打开", "提示");
                        }
                        else
                        {
                            MessageBox.Show("Port is not open", "Tips");
                        }
                        return;
                    }
                    GetSysConfValue();
                }
                else if (tabControl1.SelectedTab.Name == "tabPage5")
                {

                    //GetDeviceAndSververTime(); 
                    m_testMode = 5;

                }
                else if (tabControl1.SelectedTab.Name == "tabPage6")
                {
                    if (!m_isPortOpen)
                    {
                        if (strLang == "ChineseSimplified")
                        {
                            MessageBox.Show("串口未打开", "提示");
                        }
                        else
                        {
                            MessageBox.Show("Port is not open", "Tips");
                        }
                        return;
                    }
                    //GetDeviceAndSververTime(); 
                    m_testMode = 6;

                }
                else if (tabControl1.SelectedTab.Name == "tabPage7")
                {


                    ShowAlarmHistoryList(1);

                }
                else if (tabControl1.SelectedTab.Name == "tabPage8")
                {

                    ReadNeiZuAlarmSet();
                    //GetDeviceAndSververTime(); 
                    m_testMode = 8;

                }
                else if (tabControl1.SelectedTab.Name == "tabPage9")
                {

                    //GetDeviceAndSververTime(); 
                    GetAlarmStatus();

                }
                else if (tabControl1.SelectedTab.Name == "tabPage10")
                {

                    //GetDeviceAndSververTime(); 
                    ReadDevelopmentTest();

                }
                else if (tabControl1.SelectedTab.Name == "tabPage11")
                {

                    if (strLang == "ChineseSimplified")
                    {
                        if (!m_isPortOpen)
                        {
                            MessageBox.Show("串口未打开", "提示");
                            return;
                        }
                        if (!m_SystemRight)
                        {
                            MessageBox.Show("没有查看权限", "提示");
                            return;
                        }
                    }
                    else
                    {
                        if (!m_isPortOpen)
                        {
                            MessageBox.Show("Serial port is not opened", "TIPS");
                            return;
                        }
                        if (!m_SystemRight)
                        {
                            MessageBox.Show("No view permission!", "TIPS");
                            return;
                        }
                    }

                    //GetDeviceAndSververTime(); 
                    m_testMode = 11;

                }
                else if (tabControl1.SelectedTab.Name == "tabPage13")
                {
                    if (!m_isPortOpen)
                    {
                        if (strLang == "ChineseSimplified")
                        {
                            MessageBox.Show("串口未打开", "提示");
                        }
                        else
                        {
                            MessageBox.Show("Port is not open", "Tips");
                        }
                        return;
                    }
                    //先清空设置
                    recover_KOCheckBoxes();
                    //设置选择框的内容
                    button_KOupdate_Click(sender, e);
                }
                else if (tabControl1.SelectedTab.Name == "tabPage16")
                {
                    m_SelectIndex = 15;
                    Console.WriteLine("tabPage Changed to index 15");
                }
                else if (tabControl1.SelectedTab.Name == "tabPage17")
                {
                    m_SelectIndex = 16;
                    Console.WriteLine("tabPage Changed to index 16");
                }
            }
            catch (Exception ex)
            {
 
            }
            
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            GetParamTestValue();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            if (!m_DebugRight)
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("没有修改权限", "提示");
                else
                    MessageBox.Show("No permission to modify", "TIPS");
                return;
            }

            if (textBox36.Text == "")
            {
                if (strLang == "ChineseSimplified")
                MessageBox.Show("设置值不能为空", "提示");
                else
                MessageBox.Show("Setting value cannot be empty", "TIPS");
                return;
            }

            ushort[] registerhold = new ushort[1];

            registerhold[0] = Convert.ToUInt16(textBox36.Text);

            bool bhold = ModbusRtu.SendFc16(m_iDeviceAddr, 2089, 1, registerhold);//电池节数
            
            if (bhold)
            {
                if (strLang == "ChineseSimplified")
                MessageBox.Show("设置成功", "提示");
                else
                MessageBox.Show("Setting successfully", "TIPS");
                m_iDeviceAddr =(byte)registerhold[0];
                GetSysConfValue();
            }
            else
            {
                if (strLang == "ChineseSimplified")
                MessageBox.Show("设置失败", "提示");
                else
                MessageBox.Show("Setting failed", "TIPS");
            }
        }

        private void button11_Click(object sender, EventArgs e)
        {
            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            if (strLang == "ChineseSimplified")
            label39.Text = "正在获取时间...";
            else
            label39.Text = "Getting time now...";
            textBox26.Text = "";
            textBox27.Text = "";
            thread_poll2 = new Thread(new ThreadStart(Poll_Thread2));
            thread_poll2.Start();
        }
        private string GetCurrDevTestMode(ushort[] registerhold)
        {
            string strValue = "";
             Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
          
            switch (registerhold[0])
            { 
                case 0:
                    if (strLang == "ChineseSimplified")
                    strValue = "模式0，关闭内阻定时测量功能";
                    else
                    strValue = "Mode 0, turn off timing measurement function";
                    label48.Text = "";
                    break;
                case 1:
                    if (strLang == "ChineseSimplified")
                    strValue = "模式1，每N分钟测量一次内阻";
                    else
                    strValue = "Mode 1, resistance is measured every N minutes";
                    label48.Text = "内阻测量计时间隔:" + registerhold[5]+"分钟";
                    break;
                case 2:
                    if (strLang == "ChineseSimplified")
                    strValue = "模式2，每N小时测量一次内阻";
                    else
                    strValue = "Mode 2, measure the resistance every N hours";
                    label48.Text = "内阻测量计时间隔:" + registerhold[6] + "小时 实时" + registerhold[6]+"分钟";
                    break;
                case 3:
                    if (strLang == "ChineseSimplified")
                    strValue = "模式3，每天测量一次内阻";
                    else
                    strValue = "Mode 3, measure the resistance once a day";
                    label48.Text = "每天:" + registerhold[3] + "时" + registerhold[4] + "分"; ;
                    break;
                case 4:
                    if (strLang == "ChineseSimplified")
                    strValue = "模式4，每周测量一次内阻";
                    else
                   strValue = "Mode 4, measure the resistance once a week";
                    if (registerhold[1] == 0)
                    {
                        label48.Text = "每周日: " + registerhold[3] + "时" + registerhold[4] + "分";
                    }
                    else
                    {
                        label48.Text = "每周:" + registerhold[1] +" " + registerhold[3] + "时" + registerhold[4] + "分";
                    }
                    break;
                case 5:
                    if (strLang == "ChineseSimplified")
                    strValue = "模式5，每月测量一次内阻";
                    else
                    strValue = "Mode 5, measure the resistance once a month";
                    label48.Text = "每月:" + registerhold[2] + "日" + registerhold[3] + "时" + registerhold[4] + "分";
                    break;
                /* 您可以有任意数量的 case 语句 */
                default: /* 可选的 */
                    strValue = "";
                    break;
            }
            return strValue;
        }
        private void GetDeviceTestModeInfo()
        {
            ushort[] registerhold = new ushort[7];
            bool bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 2150, 7, ref registerhold);//电池节数
            if (bhold)
            {
                label40.Text = GetCurrDevTestMode(registerhold);


                comboBox6.SelectedIndex = registerhold[0];
                //comboBox6.Text = registerhold[0].ToString();
                textBox25.Text = registerhold[1].ToString();
                textBox29.Text = registerhold[2].ToString();
                textBox30.Text = registerhold[3].ToString();
                textBox31.Text = registerhold[4].ToString();
                textBox32.Text = registerhold[5].ToString();
                textBox33.Text = registerhold[6].ToString();

            }
        }
        private void button12_Click(object sender, EventArgs e)
        {
            GetDeviceTestModeInfo();
        }

        private void button9_Click(object sender, EventArgs e)
        {
            int value = comboBox6.SelectedIndex;

            /*if (value == 2)
            {
 
            }*/
            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            if (!m_DebugRight)
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("没有修改权限", "提示");
                else
                    MessageBox.Show("No permission to modify", "TIPS");
                return;
            }
            if (comboBox6.Text == "")
            {
                if (strLang == "ChineseSimplified")
                MessageBox.Show("设置值不能为空", "提示");
                else
                MessageBox.Show("Setting value cannot be empty", "TIPS");
                return;
            }

            if (textBox25.Text == "")
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("周值不能为空", "提示");
                else
                    MessageBox.Show("Week value cannot be empty", "TIPS");
                return;
            }
            if (textBox29.Text == "")
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("日值不能为空", "提示");
                else
                    MessageBox.Show("Daily value cannot be empty", "TIPS");
                return;
            }
            if (textBox30.Text == "")
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("时值不能为空", "提示");
                else
                    MessageBox.Show("Hour value cannot be empty", "TIPS");
                return;
            }
            if (textBox31.Text == "")
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("分值不能为空", "提示");
                else
                    MessageBox.Show("Minute value cannot be empty", "TIPS");
                return;
            }
            if (textBox32.Text == "")
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("内阻测量间隔分钟不能为空", "提示");
                else
                    MessageBox.Show("RES MEAS interval minutes cannot be empty", "TIPS");
                return;
            }
            if (textBox33.Text == "")
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("内阻测量间隔小时不能为空", "提示");
                else
                    MessageBox.Show("RES MEAS interval hours cannot be empty", "TIPS");
                return;
            }

            ushort[] registerhold = new ushort[7];

            registerhold[0] = (ushort)value;
            registerhold[1] = Convert.ToByte(textBox25.Text);
            registerhold[2] = Convert.ToByte(textBox29.Text);
            registerhold[3] = Convert.ToByte(textBox30.Text);
            registerhold[4] = Convert.ToByte(textBox31.Text);
            registerhold[5] = Convert.ToByte(textBox32.Text);
            registerhold[6] = Convert.ToByte(textBox33.Text);


            bool bhold=ModbusRtu.SendFc16(m_iDeviceAddr, 2150, 7,registerhold);//电池节数
            if (bhold)
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("设置成功", "提示");
                else
                    MessageBox.Show("Setting successfully", "TIPS");
                GetDeviceTestModeInfo();
            }
            else
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("设置失败", "提示");
                else
                    MessageBox.Show("Setting failed", "TIPS");
            }

            
            //registerhold
        }
        private  ushort GetWeekName(DayOfWeek week)
        {
            ushort weekvalue = 0;
            switch (week)
            {
                case DayOfWeek.Monday:
                    weekvalue = 1;
                    break;
                case DayOfWeek.Tuesday:
                    weekvalue = 2;
                    break;
                case DayOfWeek.Wednesday:
                    weekvalue = 3;
                    break;
                case DayOfWeek.Thursday:
                    weekvalue = 4;
                    break;
                case DayOfWeek.Friday:
                    weekvalue =5;
                    break;
                case DayOfWeek.Saturday:
                    weekvalue = 6;
                    break;
                case DayOfWeek.Sunday:
                    weekvalue = 0;
                    break;
            }
            return weekvalue;
        }
        private string GetWeekFromEnToChName(DayOfWeek week)
        {
            string name = "";
            switch (week)
            {
                case DayOfWeek.Monday:
                    name = "星期一";
                    break;
                case DayOfWeek.Tuesday:
                    name = "星期二";
                    break;
                case DayOfWeek.Wednesday:
                    name = "星期三";
                    break;
                case DayOfWeek.Thursday:
                    name = "星期四";
                    break;
                case DayOfWeek.Friday:
                    name = "星期五";
                    break;
                case DayOfWeek.Saturday:
                    name = "星期六";
                    break;
                case DayOfWeek.Sunday:
                    name = "星期日";
                    break;
            }
            return name;
        }
        private void button10_Click(object sender, EventArgs e)
        {
            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            if (!m_DebugRight)
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("没有修改权限", "提示");
                else
                    MessageBox.Show("No permission to modify", "TIPS");
                return;
            }
            
            ushort[] registerhold = new ushort[7];
            DateTime time;

            string current = GetBeijingTime();
            if (current == "") GetBeijingTime();
            if (current == "")
            {
                time = DateTime.Now.ToLocalTime();
                //Value2 = time.Year + "年" + time.Month + "月" + time.Day + " " + time.DayOfWeek + " " + time.Hour + "时" + time.Minute + "分" + time.Second + "秒 ";
                //textBox27.Text = Value;
            }
            else
            {
                 time = Convert.ToDateTime(current);
                //Value2 = Convert.ToDateTime(current).ToString("yyyy年MM月dd dddd HH时mm分ss秒");
            }

            registerhold[0] = (ushort)time.Year;
            registerhold[1] = (ushort)time.Month;
            registerhold[2] = (ushort)time.Day;
            registerhold[3] = GetWeekName(time.DayOfWeek);
            registerhold[4] = (ushort)time.Hour;
            registerhold[5] = (ushort)time.Minute;
            registerhold[6] = (ushort)time.Second;

            bool bhold = ModbusRtu.SendFc16(m_iDeviceAddr, 2100, 7, registerhold);//电池节数
            if (bhold)
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("设置成功", "提示");
                else
                    MessageBox.Show("Setting successfully", "TIPS");
                //GetParamTestValue();
            }
            else
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("设置失败", "提示");
                else
                    MessageBox.Show("Setting failed", "TIPS");
            }
        }

        private void button8_Click(object sender, EventArgs e)
        {
            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();

            if (!m_isPortOpen)
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("串口未打开","提示");
                else
                    MessageBox.Show("Serial port is not opened","TIPS");
                return;
            }
            if (!m_DebugRight)
            {
                if (strLang == "ChineseSimplified")
                MessageBox.Show("没有修改权限", "提示");
                else
                    MessageBox.Show("No permission to modify", "TIPS");
                return;
            }
            if (textBox34.Text == "")
            {
                if (strLang == "ChineseSimplified")
                MessageBox.Show("设置值不能为空", "提示");
                else
                    MessageBox.Show("value cannot be empty", "TIPS");
                return;
            }
            if (textBox24.Text == "255")
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("当前值为255,请检查接线", "提示");
                else
                    MessageBox.Show("the current value is 255 which cannot be setted ", "TIPS");
                return;
            }
            ushort[] registerhold = new ushort[1];

            
            registerhold[0] =(ushort)( 0xFA00| Convert.ToByte(textBox34.Text));
     

            bool bhold = ModbusRtu.SendFc6(m_iDeviceAddr, 2306,1, registerhold);//电池节数

            if (bhold)
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("设置成功", "提示");
                else
                    MessageBox.Show("Setting successfully", "TIPS");
                ShowBatModuleAddr();
            }
            else
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("设置失败", "提示");
                else
                    MessageBox.Show("Setting failed", "TIPS");
            }

           
            
        }

        private void button13_Click(object sender, EventArgs e)
        {
            if (m_isPortOpen)
            {
                ShowBatModuleAddr();
            }
            else
            {
                Language lang = this.CurrentSelectedLanguage;
                string strLang = lang.ToString();

                
               if (strLang == "ChineseSimplified")
                 MessageBox.Show("串口未打开", "提示");
               else
                 MessageBox.Show("Serial port is not opened", "TIPS");
               return;
                
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            if (!m_DebugRight)
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("没有修改权限", "提示");
                else
                    MessageBox.Show("No permission to modify", "TIPS");
                return;
            }
            if (textBox35.Text == "")
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("设置值不能为空", "提示");
                else
                    MessageBox.Show("Setting value cannot be empty", "TIPS");
                return;
            }
            ushort[] registerhold = new ushort[1];

            registerhold[0] = Convert.ToUInt16(textBox35.Text);
           
            bool bhold = ModbusRtu.SendFc16(m_iDeviceAddr, 2001, 1, registerhold);//电池节数
            if (bhold)
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("设置成功", "提示");
                else
                    MessageBox.Show("Setting successfully", "TIPS");
                GetSysConfValue();
            }
            else
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("设置失败", "提示");
                else
                    MessageBox.Show("Setting failed", "TIPS");
            }
           
        }

        private void button4_Click(object sender, EventArgs e)
        {
            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();

            if (!m_isPortOpen)
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("串口未打开", "提示");
                else
                    MessageBox.Show("Serial port is not opened", "TIPS");
                return;
            }
            if (!m_DebugRight)
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("没有修改权限", "提示");
                else
                    MessageBox.Show("No permission to modify", "TIPS");
                return;
            }
            try
            {
                if (textBox5.Text == "" || textBox6.Text == "" || textBox7.Text == "" || textBox8.Text == "" || textBox9.Text == "")
                {
                    if (strLang == "ChineseSimplified")
                        MessageBox.Show("设置值不能为空", "提示");
                    else
                        MessageBox.Show("Setting value cannot be empty", "TIPS");
                    return;
                }

                if (textBox10.Text == "" || textBox11.Text == "" || textBox12.Text == "" || textBox13.Text == "" || textBox14.Text == "")
                {
                    if (strLang == "ChineseSimplified")
                        MessageBox.Show("设置值不能为空", "提示");
                    else
                        MessageBox.Show("Setting value cannot be empty", "TIPS");
                    return;
                }

                if (textBox15.Text == "" || textBox16.Text == "" || textBox17.Text == "" || textBox18.Text == "" || textBox19.Text == "" || textBox20.Text == "" || textBox21.Text == "")
                {
                    if (strLang == "ChineseSimplified")
                        MessageBox.Show("设置值不能为空", "提示");
                    else
                        MessageBox.Show("Setting value cannot be empty", "TIPS");
                    return;
                }

                if (textBox38.Text == "" || textBox39.Text == "" || textBox40.Text == "" || textBox41.Text == "" || textBox42.Text == "")
                {
                    if (strLang == "ChineseSimplified")
                        MessageBox.Show("设置值不能为空", "提示");
                    else
                        MessageBox.Show("Setting value cannot be empty", "TIPS");
                    return;
                }
                button4.Enabled = false;
                ushort[] registerhold = new ushort[15];

                registerhold[0] = Convert.ToUInt16(textBox5.Text);
                registerhold[1] = Convert.ToUInt16(textBox6.Text);
                registerhold[2] = Convert.ToUInt16(textBox7.Text);

                registerhold[3] = Convert.ToUInt16(textBox10.Text);

                registerhold[4] = Convert.ToUInt16(Convert.ToSingle(textBox9.Text) * 1000);
                registerhold[5] = Convert.ToUInt16(Convert.ToSingle(textBox8.Text) * 1000);

                registerhold[6] = Convert.ToUInt16(Convert.ToSingle(textBox13.Text) * 10);

                registerhold[7] = Convert.ToUInt16(Convert.ToSingle(textBox12.Text) * 10);

                registerhold[8] = Convert.ToUInt16(textBox11.Text);


                registerhold[9] = Convert.ToUInt16(textBox16.Text);
                registerhold[10] = Convert.ToUInt16(textBox15.Text);
                registerhold[11] = Convert.ToUInt16(textBox70.Text);

                bool bhold = ModbusRtu.SendFc16(m_iDeviceAddr, 2004, 12, registerhold);//电池节数

                Thread.Sleep(100);
                //////////////////
               // ushort[] registerhold2 = new ushort[3];


                registerhold[0] = Convert.ToUInt16(textBox14.Text);
                registerhold[1] = Convert.ToUInt16(textBox71.Text);
                registerhold[2] = Convert.ToUInt16(textBox72.Text);


                bhold = ModbusRtu.SendFc16(m_iDeviceAddr, 2016, 3, registerhold);//电池节数
                ///////////////


               // Thread.Sleep(100);
               // bhold = ModbusRtu.SendFc16(m_iDeviceAddr, 2019, 5, registerhold);//电池节数
                
                
                
                ////////////////////////////
                registerhold[0] = Convert.ToUInt16(textBox19.Text);
                registerhold[1] = Convert.ToUInt16(textBox18.Text);
                registerhold[2] = Convert.ToUInt16(textBox17.Text);

                registerhold[3] = Convert.ToUInt16(textBox21.Text);
                registerhold[4] = Convert.ToUInt16(textBox20.Text);
                Thread.Sleep(100);
                bhold = ModbusRtu.SendFc16(m_iDeviceAddr, 2019, 5, registerhold);//电池节数
                /*if (bhold)
                {
                    MessageBox.Show("设置成功");
                    GetParamTestValue();
                }
                else
                {
                    MessageBox.Show("设置失败");
                }*/
                ///////////////////////////////
                registerhold[0] = Convert.ToUInt16(textBox65.Text);
                registerhold[1] = Convert.ToUInt16(textBox64.Text);
                registerhold[2] = Convert.ToUInt16(Convert.ToSingle(textBox63.Text) * 1000);
                registerhold[3] = Convert.ToUInt16(Convert.ToSingle(textBox62.Text) * 1000);
                registerhold[4] = Convert.ToUInt16(Convert.ToSingle(textBox61.Text) * 10);
                registerhold[5] = Convert.ToUInt16(Convert.ToSingle(textBox60.Text) * 10);

                registerhold[6] = Convert.ToUInt16(textBox59.Text);
                registerhold[7] = Convert.ToUInt16(Convert.ToSingle(textBox58.Text) * 1000);

                registerhold[8] = Convert.ToUInt16(Convert.ToSingle(textBox57.Text) * 1000);
                registerhold[9] = Convert.ToUInt16(Convert.ToSingle(textBox56.Text) * 1000);
                registerhold[10] = Convert.ToUInt16(Convert.ToSingle(textBox55.Text) * 1000);
                registerhold[11] = Convert.ToUInt16(Convert.ToSingle(textBox54.Text) * 1000);
                registerhold[12] = Convert.ToUInt16(Convert.ToSingle(textBox53.Text) * 1000);
                registerhold[13] = Convert.ToUInt16(Convert.ToSingle(textBox52.Text) * 1000);
                registerhold[14] = Convert.ToUInt16(Convert.ToSingle(textBox51.Text) * 1000);

                bhold = ModbusRtu.SendFc16(m_iDeviceAddr, 2024, 15, registerhold);//电池节数

                ///////////////////////// add by zhm20200414
                ////////////////////////////
                registerhold[0] = Convert.ToUInt16(textBox66.Text);
                registerhold[1] = Convert.ToUInt16(textBox67.Text);
                registerhold[2] = Convert.ToUInt16(textBox68.Text);
                registerhold[3] = Convert.ToUInt16(textBox69.Text);



                registerhold[4] = Convert.ToUInt16(textBox38.Text);
                registerhold[5] = Convert.ToUInt16(Convert.ToSingle(textBox39.Text) * 1000);
                registerhold[6] = Convert.ToUInt16(Convert.ToSingle(textBox40.Text) * 1000);

                registerhold[7] = Convert.ToUInt16(Convert.ToSingle(textBox41.Text) * 1000);
                registerhold[8] = Convert.ToUInt16(Convert.ToSingle(textBox42.Text) * 1000);

                Thread.Sleep(100);
                bhold = ModbusRtu.SendFc16(m_iDeviceAddr, 2080, 9, registerhold);//
                if (bhold)
                {
                    if (strLang == "ChineseSimplified")
                        MessageBox.Show("设置成功", "提示");
                    else
                        MessageBox.Show("Setting successfully", "TIPS");
                    GetParamTestValue();
                }
                else
                {
                    if (strLang == "ChineseSimplified")
                        MessageBox.Show("设置失败", "提示");
                    else
                        MessageBox.Show("Setting failed", "TIPS");
                }

                
            }
            catch (Exception ex)
            {
                MessageBox.Show("设置值异常", "提示");
            }
            button4.Enabled = true;
        }

        

        private void button5_Click(object sender, EventArgs e)
        {

            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            ushort[] registerhold = new ushort[1];


            //registerhold[0] = (ushort)(0xFA00 | Convert.ToByte(textBox34.Text));
            registerhold[0] = (ushort)0x5A5A;

            bool bhold = ModbusRtu.SendFc6(m_iDeviceAddr, 2302, 1, registerhold);//电池节数

            if (bhold)
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("设置成功", "提示");
                else
                    MessageBox.Show("Setting successfully", "TIPS");
                //GetParamTestValue();
            }
            else
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("设置失败", "提示");
                else
                    MessageBox.Show("Setting failed", "TIPS");
            }
        }

       

        private void button14_Click_1(object sender, EventArgs e)
        {


            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            if (m_isPortOpen)
            {
                button12.Enabled = false;

                ushort[] registerhold = new ushort[1];
                bool bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 2000, 1, ref registerhold);//版本
                if (bhold)
                {

                    label19.ForeColor = Color.Blue;
                    label19.Text = registerhold[0].ToString();

                }
                else
                {
                    label19.ForeColor = Color.Red;
                    if (strLang == "ChineseSimplified")
                    label19.Text = "通信错误!";
                    else
                    label19.Text = "Commun error!";
                   
                }
                button12.Enabled = true;
            }
            else
            {
          
                if (!m_isPortOpen)
                {
                    if (strLang == "ChineseSimplified")
                        MessageBox.Show("串口未打开", "提示");
                    else
                        MessageBox.Show("Serial port is not opened", "TIPS");
                    return;
                }
                
            }
        }

        private void 设置登陆ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form2 Dessetdlg = new Form2();
            DialogResult resut;
            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            if (strLang == "ChineseSimplified")
            {
                Dessetdlg.Text = "输入密码";
                Dessetdlg.button1.Text = "登录";
            }
            else
            {
                Dessetdlg.Text = "Enter password";
                Dessetdlg.button1.Text = "Login";
            }
            resut = Dessetdlg.ShowDialog();
           
            if (resut == DialogResult.OK)
            {
                //Application.Run(new Form1(Dessetdlg.iLogType, Dessetdlg.m_user));
                //Application.Run(new Form1());
                string strValue = this.Text;
                int character = Dessetdlg.getCharacter();//获取角色 
                if (character == 0)//管理员角色
                {
                    if (strLang == "ChineseSimplified")
                        strValue = "BAT6.1 V2.00.08(管理员)";
                    else
                        strValue = "BAT6.1 V2.00.08(Admin)";
                    setTabPageVisable(0);//设置角色的显示页面

                }
                else// (character == 1)//超级管理员角色{
                {
                    if (strLang == "ChineseSimplified")
                        strValue = "BAT6.1 V2.00.08(超级管理员)";
                    else
                        strValue = "BAT6.1 V2.00.08(SuperAdmin)";
                    setTabPageVisable(1);//超级管理员的显示页面
                    DataGridView_3_4_SetLanguageText();
                }
                this.Text = strValue;
                m_DebugRight = true;
                if (Dessetdlg.SystemRight)
                    m_SystemRight = true;
            }
        }

        private void setTabPageVisable(int character)//设置角色的显示页面
        {
            switch (character)
            {
                case 0://用户和管理员
                    tabPage13.Parent = null;//隐藏KO
                    tabPage14.Parent = null;//隐藏内阻
                    tabPage15.Parent = null;//隐藏温度
                    tabPage16.Parent = null;//隐藏历史1
                    tabPage17.Parent = null;//隐藏历史2
                    tabPage19.Parent = null;//隐藏历史2
                    break;
                case 1:
                    tabPage13.Parent = tabControl1;//显示KO
                    tabPage14.Parent = tabControl1;//显示内阻
                    tabPage15.Parent = tabControl1;//显示温度
                    tabPage16.Parent = tabControl1;//显示历史1
                    tabPage17.Parent = tabControl1;//显示历史2
                    tabPage19.Parent = tabControl1;//显示单体版本号
                    break;
            }
            
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                m_Runing = false;
                isRunningHistory0 = false;
                if (m_isPortOpen)
                    ModbusRtu.Close();

            }
            catch (Exception ex)
            { 

            }

        }
        private void ConfirmDeleteList(byte count)
        {
            if (listView1.Items.Count > count)
            {
                listView1.Items.Clear();
            }
        }

        private void comboBox6_SelectedIndexChanged(object sender, EventArgs e)
        {
            int seleindex = comboBox6.SelectedIndex;
            

            if (seleindex == 0)//
            {
                textBox25.Visible = false;  //周
                textBox29.Visible = false;  //日
                textBox30.Visible = false;  //时
                textBox31.Visible = false;  //分
                textBox32.Visible = false;  //内阻测量计时间隔-分钟
                textBox33.Visible = false;  //内阻测量计时间隔-小时

                label42.Visible = false;
                label43.Visible = false;
                label44.Visible = false;
                label45.Visible = false;
                label46.Visible = false;
                label47.Visible = false;
            }
            else if (seleindex == 1)//模式1
            {
                textBox25.Visible = false;  //周
                textBox29.Visible = false;  //日
                textBox30.Visible = false;  //时
                textBox31.Visible = false;  //分
                textBox32.Visible = true;  //内阻测量计时间隔-分钟
                textBox33.Visible = false;  //内阻测量计时间隔-小时

                label42.Visible = false;
                label43.Visible = false;
                label44.Visible = false;
                label45.Visible = false;
                label46.Visible = true;
                label47.Visible = false;
            }
            else if (seleindex == 2)//模式2
            {
                textBox25.Visible = false;  //周
                textBox29.Visible = false;  //日
                textBox30.Visible = false;  //时
                textBox31.Visible = false;  //分
                textBox32.Visible = true;  //内阻测量计时间隔-分钟
                textBox33.Visible = true;  //内阻测量计时间隔-小时

                label42.Visible = false;
                label43.Visible = false;
                label44.Visible = false;
                label45.Visible = false;
                label46.Visible = true;
                label47.Visible = true;
            }
            else if (seleindex == 3)//模式3
            {
                textBox25.Visible = false;  //周
                textBox29.Visible = false;  //日
                textBox30.Visible = true;  //时
                textBox31.Visible = true;  //分
                textBox32.Visible = false; //内阻测量计时间隔-分钟
                textBox33.Visible = false; //内阻测量计时间隔-小时

                label42.Visible = false;
                label43.Visible = false;
                label44.Visible = true;
                label45.Visible = true;
                label46.Visible = false;
                label47.Visible = false;
            }
            else if (seleindex == 4)//模式4
            {
                textBox25.Visible = true;  //周
                textBox29.Visible = false;  //日
                textBox30.Visible = true;  //时
                textBox31.Visible = true;  //分
                textBox32.Visible = false;  //内阻测量计时间隔-分钟
                textBox33.Visible = false;  //内阻测量计时间隔-小时

                label42.Visible = true;
                label43.Visible = false;
                label44.Visible = true;
                label45.Visible = true;
                label46.Visible = false;
                label47.Visible = false;
            }
            else if (seleindex == 5)//模式5
            {
                textBox25.Visible = false;  //周
                textBox29.Visible = true;  //日
                textBox30.Visible = true;  //时
                textBox31.Visible = true;  //分
                textBox32.Visible = false; //内阻测量计时间隔-分钟
                textBox33.Visible = false; //内阻测量计时间隔-小时

                label42.Visible = false;
                label43.Visible = true;
                label44.Visible = true;
                label45.Visible = true;
                label46.Visible = false;
                label47.Visible = false;
            }
        }

        private void button15_Click(object sender, EventArgs e)
        {
            m_Runing = false;
            if (m_isPortOpen)
            {
                if (thread_poll !=null) if(thread_poll.IsAlive == true)  thread_poll.Abort();
                if (thread_poll2 != null) if(thread_poll2.IsAlive == true) thread_poll2.Abort();
                if (thread_poll3 != null) if(thread_poll3.IsAlive == true) thread_poll3.Abort();
                ModbusRtu.Close();
                m_isPortOpen = false;
                button41.Enabled = false;
                label6.ForeColor = Color.Red;
                label6.Text = strcom + "已关闭!";
            }
        }
        bool IsNumeric(string str) //接收一个string类型的参数,保存到str里
        {
            if (str == null || str.Length == 0)    //验证这个参数是否为空
                return false;                           //是，就返回False
            ASCIIEncoding ascii = new ASCIIEncoding();//new ASCIIEncoding 的实例
            byte[] bytestr = ascii.GetBytes(str);         //把string类型的参数保存到数组里

            foreach (byte c in bytestr)                   //遍历这个数组里的内容
            {
                if (c < 48 || c > 57)                          //判断是否为数字
                {
                    return false;                              //不是，就返回False
                }
            }
            return true;                                        //是，就返回True
        }
        private void domainUpDown1_SelectedItemChanged(object sender, EventArgs e)
        {
            try
            {
                if (domainUpDown1.Text != "")
                {
                    if (!IsNumeric(domainUpDown1.Text))
                    {
                        //MessageBox.Show("必须为数字!");
                    }
                    else
                    {
                        m_iDeviceAddr = Convert.ToByte(domainUpDown1.Text);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("范围0-255");
                domainUpDown1.Text = "";
            }
            //m_iDeviceAddr = Convert.ToByte(domainUpDown1.Text);
           // domainUpDown1.Text = "";
        }

        private void textBox35_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                //if (e.KeyChar == '.') return;

                e.Handled = true;
                // MessageBox.Show("dd");
            }
            else
            {

            }
        }

        private void textBox36_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                //if (e.KeyChar == '.') return;

                e.Handled = true;
                // MessageBox.Show("dd");
            }
            else
            {

            }
        }

        private void textBox5_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                //if (e.KeyChar == '.') return;

                e.Handled = true;
                // MessageBox.Show("dd");
            }
            else
            {

            }
        }

        private void textBox6_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                //if (e.KeyChar == '.') return;

                e.Handled = true;
                // MessageBox.Show("dd");
            }
            else
            {

            }
        }

        private void textBox7_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                //if (e.KeyChar == '.') return;

                e.Handled = true;
                // MessageBox.Show("dd");
            }
            else
            {

            }
        }

        private void textBox10_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                //if (e.KeyChar == '.') return;

                e.Handled = true;
                // MessageBox.Show("dd");
            }
            else
            {

            }
        }

        private void textBox9_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                if (e.KeyChar == '.') return;

                e.Handled = true;
                // MessageBox.Show("dd");
            }
            else
            {

            }
        }

        private void textBox8_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                if (e.KeyChar == '.') return;

                e.Handled = true;
                // MessageBox.Show("dd");
            }
            else
            {

            }
        }

        private void textBox13_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                //if (e.KeyChar == '.') return;

                e.Handled = true;
                // MessageBox.Show("dd");
            }
            else
            {

            }
        }

        private void textBox12_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                if (e.KeyChar == '.') return;

                e.Handled = true;
                // MessageBox.Show("dd");
            }
            else
            {

            }
        }

        private void textBox11_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                //if (e.KeyChar == '.') return;

                e.Handled = true;
                // MessageBox.Show("dd");
            }
            else
            {

            }
        }

        private void textBox16_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                //if (e.KeyChar == '.') return;

                e.Handled = true;
                // MessageBox.Show("dd");
            }
            else
            {

            }
        }

        private void textBox15_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                //if (e.KeyChar == '.') return;

                e.Handled = true;
                // MessageBox.Show("dd");
            }
            else
            {

            }
        }

        private void textBox14_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                //if (e.KeyChar == '.') return;

                e.Handled = true;
                // MessageBox.Show("dd");
            }
            else
            {

            }
        }

        private void textBox19_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                //if (e.KeyChar == '.') return;

                e.Handled = true;
                // MessageBox.Show("dd");
            }
            else
            {

            }
        }

        private void textBox18_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                //if (e.KeyChar == '.') return;

                e.Handled = true;
                // MessageBox.Show("dd");
            }
            else
            {

            }
        }

        private void textBox17_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                //if (e.KeyChar == '.') return;

                e.Handled = true;
                // MessageBox.Show("dd");
            }
            else
            {

            }
        }

        private void textBox21_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                //if (e.KeyChar == '.') return;

                e.Handled = true;
                // MessageBox.Show("dd");
            }
            else
            {

            }
        }

        private void textBox20_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                //if (e.KeyChar == '.') return;

                e.Handled = true;
                // MessageBox.Show("dd");
            }
            else
            {

            }
        }

        private void textBox34_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                //if (e.KeyChar == '.') return;

                e.Handled = true;
                // MessageBox.Show("dd");
            }
            else
            {

            }
        }

        private void textBox25_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                //if (e.KeyChar == '.') return;

                e.Handled = true;
                // MessageBox.Show("dd");
            }
            else
            {

            }
        }

        private void textBox29_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                //if (e.KeyChar == '.') return;

                e.Handled = true;
                // MessageBox.Show("dd");
            }
            else
            {

            }
        }

        private void textBox30_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                //if (e.KeyChar == '.') return;

                e.Handled = true;
                // MessageBox.Show("dd");
            }
            else
            {

            }
        }

        private void textBox31_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                //if (e.KeyChar == '.') return;

                e.Handled = true;
                // MessageBox.Show("dd");
            }
            else
            {

            }
        }

        private void textBox32_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                //if (e.KeyChar == '.') return;

                e.Handled = true;
                // MessageBox.Show("dd");
            }
            else
            {

            }
        }

        private void textBox33_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                //if (e.KeyChar == '.') return;

                e.Handled = true;
                // MessageBox.Show("dd");
            }
            else
            {

            }
        }

        private void domainUpDown1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                //if (e.KeyChar == '.') return;

                e.Handled = true;
                // MessageBox.Show("dd");
            }
            else
            {

            }
        }

        private void checkBox1_Click(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
                isShowCapacity = true;
            else
                isShowCapacity = false;

        }

        private void textBox38_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                //if (e.KeyChar == '.') return;

                e.Handled = true;
                // MessageBox.Show("dd");
            }
            else
            {

            }
        }

        private void button16_Click(object sender, EventArgs e)
        {
            ///////////////////////// add by zhm20200418

            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            if (!m_DebugRight)
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("没有修改权限", "提示");
                else
                    MessageBox.Show("No permission to modify", "TIPS");
                return;
            }

            if (comboBox7.Text == "" && comboBox8.Text=="")
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("设置值不能为空", "提示");
                else
                    MessageBox.Show("Setting value cannot be empty", "TIPS");
                return;
            }
            ushort[] registerhold = new ushort[2];


            ushort value = (ushort)comboBox7.SelectedIndex;
            registerhold[0] = (ushort)(value+1);

            value = (ushort)comboBox8.SelectedIndex;
            registerhold[1] = value;

            bool bhold = ModbusRtu.SendFc16(m_iDeviceAddr, 2092, 2, registerhold);//电池节数

            if (bhold)
            {            
                m_iDeviceAddr = (byte)registerhold[0];
                GetSysConfValue();
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("设置成功", "提示");
                else
                    MessageBox.Show("Setting successfully", "TIPS");
            }
            else
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("设置失败", "提示");
                else
                    MessageBox.Show("Setting failed", "TIPS");
            }
           
        }

        private void timer1_Tick(object sender, EventArgs e)
        {


            if (!m_isPortOpen)
            {
                return;
            }
            
            if (m_testMode == 11)//VC模块数据
            {
                if (!isRunning11)
                {
                    Thread thread_poll11 = new Thread(new ThreadStart(ReadRDDebug));
                    thread_poll11.Start();
                }
            }
            else if (m_testMode == 5)//最值
            {
                if (!isRunning5)
                {
                    Thread thread_poll5 = new Thread(new ThreadStart(ReadTheMaxAndMinValue));
                    thread_poll5.Start();
                }
            }
            else if (m_testMode == 6)//当前报警
            {
                if (!isRunning6)
                {
                    Thread thread_poll6 = new Thread(new ThreadStart(ShowCurrentAlarmInfo));
                    thread_poll6.Start();
                }
               
            }
            else if (m_testMode == 8)//内阻报警设置
            {
                if (!isRunning8)
                {
                   // Thread thread_poll8 = new Thread(new ThreadStart(ReadNeiZuAlarmSet));
                   // thread_poll8.Start();
                   // ReadNeiZuAlarmSet();
                }
            }
              
        }

        private void dataGridView2_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            
           
        }

        private void button21_Click(object sender, EventArgs e)
        {

         
            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            if (strLang == "ChineseSimplified")
            {
                if (!m_DebugRight)
                {
                    MessageBox.Show("没有修改权限","提示");
                    return;
                }
            }
            else
            {
                if (!m_DebugRight)
                {
                    MessageBox.Show("No permission to modify!", "Tips");
                    return;
                }
            }
            //写使能
            //dataGridView2.Rows.Count
            if (!m_isPortOpen)
            {
                if (strLang == "ChineseSimplified")
                {
                    MessageBox.Show("串口未打开！", "提示");
                }
                else
                {
                    MessageBox.Show("Serial port is not opened！", "Tips");  
                }
                return;
            }
            //string strValue= this.dataGridView2.Rows[2].Cells[1].ToString();
            DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)dataGridView2.Rows[3].Cells[3];
           
            //DataGridViewComboBoxCell cb = cell as DataGridViewComboBoxCell;
            //string baseValue = ((System.Data.DataRowView)cb.Items[1])[cb.ValueMember].ToString();//下拉列表显示内容
            //int index = (int)cell.Value;
            ushort[] registerhold = new ushort[18];
            //string strValue = dataGridView2.Rows[3].Cells[3].FormattedValue.ToString();
            string strValue = this.dataGridView2.Rows[3].Cells[1].Value.ToString();//显示值
            string strValue1 = this.dataGridView2.Rows[7].Cells[1].Value.ToString();//显示值
            string strValue2 = this.dataGridView2.Rows[11].Cells[1].Value.ToString();//显示值
            string strValue3 = this.dataGridView2.Rows[15].Cells[1].Value.ToString();//显示值

            if (strLang == "ChineseSimplified")
            {
                if (strValue == "开启")
                    registerhold[0] = 1;
                else
                    registerhold[0] = 0;

                if (strValue1 == "开启")
                    registerhold[1] = 1;
                else
                    registerhold[1] = 0;

                if (strValue2 == "开启")
                    registerhold[2] = 1;
                else
                    registerhold[2] = 0;

                if (strValue3 == "开启")
                    registerhold[3] = 1;
                else
                    registerhold[3] = 0;

            }
            else
            {
               
                if (strValue == "Open")
                    registerhold[0] = 1;
                else
                    registerhold[0] = 0;

                if (strValue1 == "Open")
                    registerhold[1] = 1;
                else
                    registerhold[1] = 0;

                if (strValue2 == "Open")
                    registerhold[2] = 1;
                else
                    registerhold[2] = 0;

                if (strValue3 == "Open")
                    registerhold[3] = 1;
                else
                    registerhold[3] = 0;
            }


            bool bhold = ModbusRtu.SendFc16(m_iDeviceAddr, 2039, 4, registerhold);//电池节数

            if (bhold)
            {
             //   MessageBox.Show("设置成功");
            }
            else
            {
              //  MessageBox.Show("设置失败");
            }


            //传感器类型
            int indextype1 = GetTypeIndex(0, 3);
            int indextype3 = GetTypeIndex(2, 3);
            int indextype4= GetTypeIndex(3, 3);
            int indextype5 = GetTypeIndex(4, 3);
            int indextype6 = GetTypeIndex(5, 3);

            int indextype7 = GetTypeIndex(6, 3);
            int indextype8 = GetTypeIndex(7, 3);
            int indextype9= GetTypeIndex(8, 3);
            int indextype10 = GetTypeIndex(9, 3);

            int indextype11 = GetTypeIndex(10, 3);
            int indextype12 = GetTypeIndex(11, 3);
            int indextype13 = GetTypeIndex(12, 3);
            int indextype14 = GetTypeIndex(13, 3);

            int indextype15 = GetTypeIndex(14, 3);
            int indextype16=  GetTypeIndex(15, 3);
            int indextype17 = GetTypeIndex(16, 3);
            int indextype18 = GetTypeIndex(17, 3);

            //电池组号
            int indexgroup1 = GetTypeIndex(0, 4);
            int indexgroup3 = GetTypeIndex(2, 4);
            int indexgroup4 = GetTypeIndex(3, 4);
            int indexgroup5 = GetTypeIndex(4, 4);
            int indexgroup6 = GetTypeIndex(5, 4);

            int indexgroup7 = GetTypeIndex(6, 4);
            int indexgroup8 = GetTypeIndex(7, 4);
            int indexgroup9 = GetTypeIndex(8, 4);
            int indexgroup10 = GetTypeIndex(9, 4);

            int indexgroup11 = GetTypeIndex(10, 4);
            int indexgroup12 = GetTypeIndex(11, 4);
            int indexgroup13 = GetTypeIndex(12, 4);
            int indexgroup14 = GetTypeIndex(13, 4);

            int indexgroup15 = GetTypeIndex(14, 4);
            int indexgroup16 = GetTypeIndex(15, 4);
            int indexgroup17 = GetTypeIndex(16, 4);
            int indexgroup18 = GetTypeIndex(17, 4);


            registerhold[0] = GetValueFromTab(indextype1, indexgroup1);
            registerhold[1] = 0;
            registerhold[2] = GetValueFromTab(indextype3, indexgroup3);
            registerhold[3] = GetValueFromTab(indextype4, indexgroup4);
            registerhold[4] = GetValueFromTab(indextype5, indexgroup5);
            registerhold[5] = GetValueFromTab(indextype6, indexgroup6);
            registerhold[6] = GetValueFromTab(indextype7, indexgroup7);
            registerhold[7] = GetValueFromTab(indextype8, indexgroup8);
            registerhold[8] = GetValueFromTab(indextype9, indexgroup9);
            registerhold[9] = GetValueFromTab(indextype10, indexgroup10);
            registerhold[10] = GetValueFromTab(indextype11, indexgroup11);
            registerhold[11] = GetValueFromTab(indextype12, indexgroup12);
            registerhold[12] = GetValueFromTab(indextype13, indexgroup13);
            registerhold[13] = GetValueFromTab(indextype14, indexgroup14);
            registerhold[14] = GetValueFromTab(indextype15, indexgroup15);
            registerhold[15] = GetValueFromTab(indextype16, indexgroup16);
            registerhold[16] = GetValueFromTab(indextype17, indexgroup17);
            registerhold[17] = GetValueFromTab(indextype18, indexgroup18);


            bhold = ModbusRtu.SendFc16(m_iDeviceAddr, 2043, 18, registerhold);//电池节数
            
            //量程
            string strRange1 = this.dataGridView2.Rows[0].Cells[5].Value.ToString();//显示值
            string strRange3 = this.dataGridView2.Rows[2].Cells[5].Value.ToString();//显示值
            string strRange4 = this.dataGridView2.Rows[3].Cells[5].Value.ToString();//显示值
            string strRange5 = this.dataGridView2.Rows[4].Cells[5].Value.ToString();//显示值
            string strRange6 = this.dataGridView2.Rows[5].Cells[5].Value.ToString();//显示值
            string strRange7 = this.dataGridView2.Rows[6].Cells[5].Value.ToString();//显示值
            string strRange8 = this.dataGridView2.Rows[7].Cells[5].Value.ToString();//显示值
            string strRange9 = this.dataGridView2.Rows[8].Cells[5].Value.ToString();//显示值
            string strRange10 = this.dataGridView2.Rows[9].Cells[5].Value.ToString();//显示值
            string strRange11 = this.dataGridView2.Rows[10].Cells[5].Value.ToString();//显示值
            string strRange12 = this.dataGridView2.Rows[11].Cells[5].Value.ToString();//显示值
            string strRange13 = this.dataGridView2.Rows[12].Cells[5].Value.ToString();//显示值
            string strRange14 = this.dataGridView2.Rows[13].Cells[5].Value.ToString();//显示值
            string strRange15 = this.dataGridView2.Rows[14].Cells[5].Value.ToString();//显示值
            string strRange16 = this.dataGridView2.Rows[15].Cells[5].Value.ToString();//显示值
            string strRange17 = this.dataGridView2.Rows[16].Cells[5].Value.ToString();//显示值
            string strRange18 = this.dataGridView2.Rows[17].Cells[5].Value.ToString();//显示值

            

            
            registerhold[0] = (ushort)Convert.ToInt32(strRange1);
            registerhold[1] = 0;
            registerhold[2] = (ushort)Convert.ToInt32(strRange3);
            registerhold[3] = (ushort)Convert.ToInt32(strRange4);
            registerhold[4] = (ushort)Convert.ToInt32(strRange5);
            registerhold[5] = (ushort)Convert.ToInt32(strRange6);
            registerhold[6] = (ushort)Convert.ToInt32(strRange7);
            registerhold[7] = (ushort)Convert.ToInt32(strRange8);
            registerhold[8] = (ushort)Convert.ToInt32(strRange9);
            registerhold[9] = (ushort)Convert.ToInt32(strRange10);
            registerhold[10] = (ushort)Convert.ToInt32(strRange11);
            registerhold[11] = (ushort)Convert.ToInt32(strRange12);
            registerhold[12] = (ushort)Convert.ToInt32(strRange13);
            registerhold[13] = (ushort)Convert.ToInt32(strRange14);
            registerhold[14] = (ushort)Convert.ToInt32(strRange15);
            registerhold[15] = (ushort)Convert.ToInt32(strRange16);
            registerhold[16] = (ushort)Convert.ToInt32(strRange17);
            registerhold[17] = (ushort)Convert.ToInt32(strRange18);
           
            bhold = ModbusRtu.SendFc16(m_iDeviceAddr, 2061, 18, registerhold);//电池节数

            if (bhold)
            {
                if (strLang == "ChineseSimplified")
                MessageBox.Show("设置成功","提示");
                else
                MessageBox.Show("Setting successfully", "提示");
                GetSysConfValue();
            }
            else
            {
                if (strLang == "ChineseSimplified")
                MessageBox.Show("设置失败","提示");
                else
                MessageBox.Show("Setting failed", "提示");
            }
        }

        private int GetTypeIndex(int row,int column)
        {
            int index = 0;
            string strValue = this.dataGridView2.Rows[row].Cells[column].Value.ToString();
            DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)dataGridView2.Rows[row].Cells[column];
            index = cell.Items.IndexOf(strValue);

            return index;
        }

        private void ReadNeiZuAlarmSet()
        {
            //public delegate void ShowYanFaDebug(string Xiangxi, string Value, int index);
            try
            {
                Language lang = this.CurrentSelectedLanguage;
                string strLang = lang.ToString();

                if (!m_isPortOpen)
                {
                    if (strLang == "ChineseSimplified")
                        MessageBox.Show("串口未打开", "提示");
                    else
                        MessageBox.Show("Serial port is not opened", "TIPS");
                    return;
                }
                
                isRunning8 = true;
                bool bhold = false;
                int index = 0;
                // ushort value = 0x01;

                ushort value = 0x01;
                float value2 = 0;


  
                string strNeiZuValue = "";
                

                textBox44.Text = "";
                textBox46.Text = "";
                textBox47.Text = "";
                textBox49.Text = "";

                ushort[] registerhold = new ushort[40];
                /////////////////读取波特率和校验位
                bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 2080, 1, ref registerhold);//
                if (bhold)
                {
    
                    comboBox9.SelectedIndex = registerhold[0];
                }
                else
                {
                    comboBox9.Text = "";                  
                }
        
                bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 2011, 1, ref registerhold);//
                if (bhold)
                {

                    value2 = (float)(registerhold[0]) / 10;
                    textBox44.Text = value2.ToString("0.0");
                }
                else
                {
                    MessageBox.Show("Get data failed!","TIPS");
                    isRunning8 = false;
                    return;
                }
                //ushort[] registerhold = new ushort[120];
                bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 2014, 1, ref registerhold);//
                if (bhold)
                {
                    textBox46.Text = registerhold[0].ToString();
                }
                else
                {
                    MessageBox.Show("Get data failed!", "TIPS");
                    isRunning8 = false;
                    return;
                }

                bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 7445, 1, ref registerhold);//
                if (bhold)
                {
                    value = registerhold[0];
                    value2 = (float)(value) / 10;
                    textBox47.Text = value2.ToString("0.0");
                }
                else
                {
                    MessageBox.Show("Get data failed!", "TIPS");
                    isRunning8 = false;
                    return;
                }

                bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 7446, 1, ref registerhold);//
                if (bhold)
                {
                    value = registerhold[0];
                    int value3 = 0;
                    if (value > 32767)
                    {
                        value3 = (value - 65536);
                        textBox49.Text = value3.ToString();
                    }
                    else
                    {
                        //value2 = (float)(value) / 10;
                        textBox49.Text = value.ToString();
                    }
                }
                else
                {
                    MessageBox.Show("Get data failed!", "TIPS");
                    isRunning8 = false;
                    return;
                }

                bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 7325, 40, ref registerhold);//
                // ShowTestCount();
                //Invoke(new InsertToList(InsertToTheMaxAndMinValue), new object[] { listView2, strIndex, Volt, Temp, NeiZu, index });

                if (bhold)
                {
                    for (int i = 0; i < 40; i ++)
                    {
                        value = registerhold[i];
                        value2 = (float)(value) / 1000;
                        strNeiZuValue = value2.ToString("0.000");
                        Invoke(new InsertToList2(InsertToNeizuchuValue), new object[] { strNeiZuValue, index });
                        index++;
                    }
                }

                bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 7365, 40, ref registerhold);//
                // ShowTestCount();
                //Invoke(new InsertToList(InsertToTheMaxAndMinValue), new object[] { listView2, strIndex, Volt, Temp, NeiZu, index });

                if (bhold)
                {
                    for (int i = 0; i < 40; i++)
                    {
                        value = registerhold[i];
                        value2 = (float)(value) / 1000;
                        strNeiZuValue = value2.ToString("0.000");
                        Invoke(new InsertToList2(InsertToNeizuchuValue), new object[] { strNeiZuValue, index });
                        index++;
                    }
                }

                bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 7405, 40, ref registerhold);//
                // ShowTestCount();
                //Invoke(new InsertToList(InsertToTheMaxAndMinValue), new object[] { listView2, strIndex, Volt, Temp, NeiZu, index });

                if (bhold)
                {
                    for (int i = 0; i < 40; i++)
                    {
                        value = registerhold[i];
                        value2 = (float)(value) / 1000;
                        strNeiZuValue = value2.ToString("0.000");
                        Invoke(new InsertToList2(InsertToNeizuchuValue), new object[] { strNeiZuValue, index });
                        index++;
                    }
                }

            }
            catch (Exception ex)
            {
                 MessageBox.Show(ex.ToString());
            }
            isRunning8 = false;
            // isRunning5 = false;
        }
        
        private void button22_Click(object sender, EventArgs e)
        {

        }

        private void dataGridView2_RowPrePaint_1(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            if (m_first) return;
            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            if (e.RowIndex == 0)
            {
                this.dataGridView2.Rows[e.RowIndex].Cells[1] = new DataGridViewTextBoxCell();
                if (strLang == "ChineseSimplified")
                this.dataGridView2.Rows[e.RowIndex].Cells[1].Value = "固定开启";
                else
                this.dataGridView2.Rows[e.RowIndex].Cells[1].Value = "Fixed opening";
                this.dataGridView2.Rows[e.RowIndex].Cells[1].ReadOnly = true;
            }
            else if (e.RowIndex == 1)
            {

                this.dataGridView2.Rows[e.RowIndex].Cells[1] = new DataGridViewTextBoxCell();
                if (strLang == "ChineseSimplified")
                this.dataGridView2.Rows[e.RowIndex].Cells[1].Value = "固定开启";
                else
                this.dataGridView2.Rows[e.RowIndex].Cells[1].Value = "Fixed opening";
                this.dataGridView2.Rows[e.RowIndex].Cells[1].ReadOnly = true;

                this.dataGridView2.Rows[e.RowIndex].Cells[3] = new DataGridViewTextBoxCell();
                if (strLang == "ChineseSimplified")
                this.dataGridView2.Rows[e.RowIndex].Cells[3].Value = "预留";
                else
                this.dataGridView2.Rows[e.RowIndex].Cells[3].Value = "Reserve";
                this.dataGridView2.Rows[e.RowIndex].Cells[3].ReadOnly = true;

                this.dataGridView2.Rows[e.RowIndex].Cells[4] = new DataGridViewTextBoxCell();
                this.dataGridView2.Rows[e.RowIndex].Cells[4].Value = "";
                this.dataGridView2.Rows[e.RowIndex].Cells[4].ReadOnly = true;

                this.dataGridView2.Rows[e.RowIndex].Cells[5] = new DataGridViewTextBoxCell();
                this.dataGridView2.Rows[e.RowIndex].Cells[5].Value = "";
                this.dataGridView2.Rows[e.RowIndex].Cells[5].ReadOnly = true;

                this.dataGridView2.Rows[e.RowIndex].Cells[6] = new DataGridViewTextBoxCell();
                this.dataGridView2.Rows[e.RowIndex].Cells[6].Value = "";
                this.dataGridView2.Rows[e.RowIndex].Cells[6].ReadOnly = true;
            }
            else
            {
                if (e.RowIndex == 3 || e.RowIndex == 7 || e.RowIndex == 11 || e.RowIndex == 15)
                    return;

                this.dataGridView2.Rows[e.RowIndex].Cells[1] = new DataGridViewTextBoxCell();
                this.dataGridView2.Rows[e.RowIndex].Cells[1].Value = "";
                this.dataGridView2.Rows[e.RowIndex].Cells[1].ReadOnly = true;
            }
            if (e.RowIndex == 17)
                m_first = true;
        }

        private void button17_Click(object sender, EventArgs e)
        {
            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            if (!m_DebugRight)
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("没有修改权限", "提示");
                else
                    MessageBox.Show("No permission to modify", "TIPS");
                return;
            }

            if (comboBox9.Text == "")
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("设置值不能为空", "提示");
                else
                    MessageBox.Show("Setting value cannot be empty", "TIPS");
                return;
            }
            ushort[] registerhold = new ushort[1];

            ushort value = (ushort)comboBox9.SelectedIndex;
            registerhold[0] = (ushort)(value);

            bool bhold = ModbusRtu.SendFc16(m_iDeviceAddr, 2080, 1, registerhold);//内阻过高报警模式
        
            registerhold[0] = Convert.ToUInt16(Convert.ToSingle(textBox44.Text) * 10);//2011
            bhold = ModbusRtu.SendFc16(m_iDeviceAddr, 2011, 1, registerhold);//

            registerhold[0] = Convert.ToUInt16(Convert.ToSingle(textBox46.Text));//2014
            bhold = ModbusRtu.SendFc16(m_iDeviceAddr, 2014, 1, registerhold);//

            registerhold[0] = Convert.ToUInt16(Convert.ToSingle(textBox47.Text) * 10);//7445
            bhold = ModbusRtu.SendFc16(m_iDeviceAddr, 7445, 1, registerhold);//

            
            ushort[] registerhold2 = new ushort[120];
            //ushort[] registerhold3 = new ushort[40];
            //ushort[] registerhold4 = new ushort[40];
            string strValue = "";
            for (int i = 0; i < dataGridView1.RowCount; i++)
            {
                strValue = dataGridView1.Rows[i].Cells[2].Value.ToString();
                registerhold2[i] = Convert.ToUInt16(Convert.ToSingle(strValue) * 1000);//2011
            }
            bhold = ModbusRtu.SendFc16(m_iDeviceAddr, 7325, 120, registerhold2);//
            if (bhold)
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("设置成功", "提示");
                else
                    MessageBox.Show("Setting successfully", "TIPS");
                //GetParamTestValue();
            }
            else
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("设置失败", "提示");
                else
                    MessageBox.Show("Setting failed", "TIPS");
            }
        }
        private void GetAlarmStatus()
        {
            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            if (strLang == "ChineseSimplified")
            {
                if (!m_isPortOpen)
                {
                    MessageBox.Show("串口未打开", "提示");
                    return;
                }
                if (!m_SystemRight)
                {
                    MessageBox.Show("没有查看权限", "提示");
                    return;
                }
            }
            else
            {
                if (!m_isPortOpen)
                {
                    MessageBox.Show("Serial port is not opened", "TIPS");
                    return;
                }
                if (!m_SystemRight)
                {
                    MessageBox.Show("No view permission!", "TIPS");
                    return;
                }
            }
            ushort[] registerhold = new ushort[2];
            ushort value = 10, value1 = 1, value2 = 0;
           // ushort value3 = 0, value4 = 1, value5 = 0,value6 = 0, value7 = 1, value8 = 0,value9 = 0, value10 = 1, value11 = 0;
           // ushort value12 = 0, value13 = 1, value14 = 0, value15 = 0, value16 = 1;
            //ushort[] registerhold = new ushort[120];
            bool bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 1000, 2, ref registerhold);//电池节数           

            if (bhold)
            {
                value = registerhold[0];
                value1 = (ushort)(value & 1);
                value2 = (ushort)((value & 2) >> 1);
                comboBox16.SelectedIndex = value1;
                comboBox18.SelectedIndex = value2;
                value1 = (ushort)(value & 1);
                value2 = (ushort)((value & 2) >> 1);
                 
                comboBox11.SelectedIndex = (ushort)((value & 4) >> 2);
                comboBox10.SelectedIndex = (ushort)((value & 8) >> 3);
                comboBox13.SelectedIndex = (ushort)((value & 16) >> 4);
                comboBox28.SelectedIndex = (ushort)((value & 32) >> 5);
                comboBox12.SelectedIndex = (ushort)((value & 64) >> 6);
                comboBox15.SelectedIndex = (ushort)((value & 128) >> 7);
                comboBox14.SelectedIndex = (ushort)((value & 256) >> 8);
                comboBox19.SelectedIndex = (ushort)((value & 512) >> 9);
                comboBox17.SelectedIndex = (ushort)((value & 1024) >> 10);
                comboBox21.SelectedIndex = (ushort)((value & 2048) >> 11);
                comboBox20.SelectedIndex = (ushort)((value & 4096) >> 12);
                comboBox23.SelectedIndex = (ushort)((value & 8192) >> 13);
                comboBox22.SelectedIndex = (ushort)((value & 16384) >> 14);
                comboBox25.SelectedIndex = (ushort)((value & 32768) >> 15);
                
                value = registerhold[1];
                comboBox24.SelectedIndex = (ushort)((value & 1) >> 0);
                //comboBox11.SelectedIndex = (ushort)((value & 2) >> 1);
                comboBox27.SelectedIndex = (ushort)((value & 4) >> 2);
                //comboBox11.SelectedIndex = (ushort)((value & 32) >> 1);
                value2 = (ushort)((value & 8) >> 3);
                comboBox26.SelectedIndex = value2;

            }
            else
            {
                comboBox16.SelectedIndex = -1;
                comboBox18.SelectedIndex = -1;

                comboBox10.SelectedIndex = -1;
                comboBox11.SelectedIndex = -1;
                comboBox13.SelectedIndex = -1;
                comboBox28.SelectedIndex = -1;
                comboBox12.SelectedIndex = -1;
                comboBox15.SelectedIndex = -1;
                comboBox14.SelectedIndex = -1;

                comboBox19.SelectedIndex = -1;
                comboBox17.SelectedIndex = -1;
                comboBox21.SelectedIndex = -1;
                comboBox20.SelectedIndex = -1;
                comboBox23.SelectedIndex = -1;
                comboBox22.SelectedIndex = -1;

                comboBox25.SelectedIndex = -1;
                comboBox24.SelectedIndex = -1;

                comboBox27.SelectedIndex = -1;
                comboBox26.SelectedIndex = -1;
            }
           
        }
        private void button32_Click(object sender, EventArgs e)
        {



            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();

            if (!m_isPortOpen)
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("串口未打开", "提示");
                else
                    MessageBox.Show("Serial port is not opened", "TIPS");
                return;
            }
            if (!m_DebugRight)
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("没有修改权限", "提示");
                else
                    MessageBox.Show("No permission to modify", "TIPS");
                return;
            }
            if (comboBox16.Text == "" && comboBox18.Text == "")
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("设置值不能为空", "提示");
                else
                    MessageBox.Show("value cannot be empty", "TIPS");
                return;
            }

            ushort[] registerhold = new ushort[2];

            //ushort[] registerhold = new ushort[120];
            bool bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 1000, 2, ref registerhold);//电池节数        


            ushort value = registerhold[0], value1 = 0, value2 = 0, value3 = 0, value4 = 0, value5 = 0, value19 = 0, value6 = 0;
            ushort  value7 = 0, value8 = 0, value9 = 0, value10 = 0, value11 = 0, value12 = 0;
            ushort value13 = 0, value14 = 0, value15 = 0, value16 = 0, value17 = 0, value18 = 0;

            ushort valueB = registerhold[1];

            value1 = (ushort)comboBox16.SelectedIndex;
            value2 = (ushort)comboBox18.SelectedIndex;


            value3 = (ushort)comboBox11.SelectedIndex;
            value4 = (ushort)comboBox10.SelectedIndex;
            value5 = (ushort)comboBox13.SelectedIndex;
            value19 = (ushort)comboBox28.SelectedIndex;
            value6 = (ushort)comboBox12.SelectedIndex;
            value7 = (ushort)comboBox15.SelectedIndex;
            value8= (ushort)comboBox14.SelectedIndex;
            value9 = (ushort)comboBox19.SelectedIndex;
            value10 = (ushort)comboBox17.SelectedIndex;
            value11 = (ushort)comboBox21.SelectedIndex;
            value12 = (ushort)comboBox20.SelectedIndex;
            value13 = (ushort)comboBox23.SelectedIndex;
            value14 = (ushort)comboBox22.SelectedIndex;
            value15 = (ushort)comboBox25.SelectedIndex;
            value16 = (ushort)comboBox24.SelectedIndex;
            value17 = (ushort)comboBox27.SelectedIndex;
            value18 = (ushort)comboBox26.SelectedIndex;


            if(value1==1)
                value = (ushort)(value | (1 << 0));
            else
                value = (ushort)(value & ~(1 << 0));

            if (value2 == 1)
                value = (ushort)(value | (1 << 1));
            else
                value = (ushort)(value & ~(1 << 1));

            if (value3== 1)
                value = (ushort)(value | (1 << 2));
            else
                value = (ushort)(value & ~(1 << 2));
           
            if (value4 == 1)
                value = (ushort)(value | (1 << 3));
            else
                value = (ushort)(value & ~(1 << 3));

            if (value5 == 1)
                value = (ushort)(value | (1 << 4));
            else
                value = (ushort)(value & ~(1 << 4));

            if (value19 == 1)
                value = (ushort)(value | (1 << 5));
            else
                value = (ushort)(value & ~(1 << 5));

            if (value6 == 1)
                value = (ushort)(value | (1 << 6));
            else
                value = (ushort)(value & ~(1 << 6));

            if (value7 == 1)
                value = (ushort)(value | (1 << 7));
            else
                value = (ushort)(value & ~(1 << 7));

            if (value8 == 1)
                value = (ushort)(value | (1 << 8));
            else
                value = (ushort)(value & ~(1 << 8));

            if (value9 == 1)
                value = (ushort)(value | (1 << 9));
            else
                value = (ushort)(value & ~(1 << 9));

            if (value10 == 1)
                value = (ushort)(value | (1 << 10));
            else
                value = (ushort)(value & ~(1 << 10));

            if (value11 == 1)
                value = (ushort)(value | (1 << 11));
            else
                value = (ushort)(value & ~(1 << 11));

            if (value12 == 1)
                value = (ushort)(value | (1 << 12));
            else
                value = (ushort)(value & ~(1 << 12));

            if (value13 == 1)
                value = (ushort)(value | (1 << 13));
            else
                value = (ushort)(value & ~(1 << 13));

            if (value14 == 1)
                value = (ushort)(value | (1 << 14));
            else
                value = (ushort)(value & ~(1 << 14));

            if (value15 == 1)
                value = (ushort)(value | (1 << 15));
            else
                value = (ushort)(value & ~(1 << 15));

            
            
            if (value16 == 1)
                valueB = (ushort)(valueB | (1 << 0));
            else
                valueB = (ushort)(valueB & ~(1 << 0));         
            
            if (value17 == 1)
                valueB = (ushort)(valueB | (1 << 2));
            else
                valueB = (ushort)(valueB & ~(1 << 2));

            if (value18 == 1)
                valueB = (ushort)(valueB | (1 << 3));
            else
                valueB = (ushort)(valueB & ~(1 << 3));

                    
            registerhold[0] = value;
            registerhold[1] = valueB;

            bhold = ModbusRtu.SendFc16(m_iDeviceAddr, 1000, 2, registerhold);//电池节数

            if (bhold)
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("设置成功", "提示");
                else
                    MessageBox.Show("Setting successfully", "TIPS");
                GetAlarmStatus();
            }
            else
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("设置失败", "提示");
                else
                    MessageBox.Show("Setting failed", "TIPS");
            }

            
        }

        private void InsertToDevelopValue(ListView listView, string strDesc,string Value, int index)
        {
            if (listView.Items.Count < index + 1)
            {
                //ListViewItem OptionItem = new ListViewItem(strName);
                ListViewItem OptionItem = new ListViewItem((index + 1).ToString());
                OptionItem.UseItemStyleForSubItems = false;
                OptionItem.SubItems.Add(strDesc);//
                OptionItem.SubItems.Add(Value);//            
                listView.Items.Add(OptionItem);//执行添加操作*/
            }
            else
            {
                listView.Items[index].SubItems[1].Text = strDesc;
                listView.Items[index].SubItems[2].Text = Value;

            }

        }


        private void ReadDevelopmentTest()
        {
            //public delegate void ShowYanFaDebug(string Xiangxi, string Value, int index);
            try
            {
                Language lang = this.CurrentSelectedLanguage;
                string strLang = lang.ToString();
                if (strLang == "ChineseSimplified")
                {
                    if (!m_isPortOpen)
                    {
                        MessageBox.Show("串口未打开", "提示");
                        return;
                    }
                    if (!m_SystemRight)
                    {
                        MessageBox.Show("没有查看权限", "提示");
                        return;
                    }
                }
                else               
                {
                    if (!m_isPortOpen)
                    {
                        MessageBox.Show("Serial port is not opened", "TIPS");
                        return;
                    }
                    if (!m_SystemRight)
                    {
                        MessageBox.Show("No view permission!", "TIPS");
                        return;
                    }
                }
                bool bhold = false;
                int index = 0;
                // ushort value = 0x01;

                ushort value = 0x01;
                float value2 = 0;
                int value3=0;


                string strValue = "";
                string strDesc = "";

               

                ushort[] registerhold = new ushort[12];
                /////////////////读取波特率和校验位
                bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 6000, 12, ref registerhold);//
               
                // ShowTestCount();
                //Invoke(new InsertToList(InsertToTheMaxAndMinValue), new object[] { listView2, strIndex, Volt, Temp, NeiZu, index });
         
                if (bhold)
                {
                    for(int i=0;i<12;i++)
                    {
                        strValue = registerhold[i].ToString();
                        if (strLang == "ChineseSimplified")
                        {
                            if (i == 0)
                                strDesc = "BAT6.1通讯成功次数";
                            if (i == 1)
                                strDesc = "BAT6.1通讯失败次数";
                            if (i == 2)
                                strDesc = "智能电压变送器通讯成功次数";
                            if (i == 3)
                                strDesc = "智能电压变送器通讯失败次数";
                            if (i == 4)
                                strDesc = "掉电时存储的FLASH地址高16bit";
                            if (i == 5)
                                strDesc = "掉电时存储的FLASH地址低16bit";
                            if (i == 6)
                                strDesc = "产品自检状态";
                            if (i == 7)
                            {
                                strDesc = "RTC补偿值(T)";
                                value = registerhold[i];
                                if (value > 32767)
                                {
                                    value3 = (value - 65536);
                                    strValue = value3.ToString();
                                }
                            }
                            if (i == 8)
                                strDesc = "BAT6.1_CJ对BAT6.1写操作成功次数计数";
                            if (i == 9)
                                strDesc = "BAT6.1_CJ对BAT6.1写操作失败次数计数";
                            if (i == 10)
                                strDesc = "BAT6.1产品地址";
                            if (i == 11)
                                strDesc = "BAT6.1软件版本";
                        }
                        else
                        {
                            if (i == 0)
                                strDesc = "BAT6.1 Communication success times";
                            if (i == 1)
                                strDesc = "BAT6.1 Communication failures times";
                            if (i == 2)
                                strDesc = "Successful communication times of intelligent voltage transmitter";
                            if (i == 3)
                                strDesc = "Communication failure times of intelligent voltage transmitter";
                            if (i == 4)
                                strDesc = "Flash high 16bit address stored during power failure";
                            if (i == 5)
                                strDesc = "Flash low 16bit address stored during power failure";
                            if (i == 6)
                                strDesc = "Product self inspection status";
                            if (i == 7)
                            {
                                strDesc = "RTC compensation value(T)";
                                value = registerhold[i];
                                if (value > 32767)
                                {
                                    value3 = (value - 65536);
                                    strValue = value3.ToString();
                                }
                            }
                            if (i == 8)
                                strDesc = "BAT6.1_CJ BAT6.1 Write success count";
                            if (i == 9)
                                strDesc = "BAT6.1_CJ BAT6.1 Write failure count";
                            if (i == 10)
                                strDesc = "BAT6.1 Product address";
                            if (i == 11)
                                strDesc = "BAT6.1 Software version";
                        }
                        Invoke(new InsertToList3(InsertToDevelopValue), new object[] { listView10, strDesc, strValue, index });
                        index++;
                    }
                }
                
               

            }
            catch (Exception ex)
            {
                // MessageBox.Show(ex.ToString());
            }

            // isRunning5 = false;
        }
        private void button34_Click(object sender, EventArgs e)
        {

        }

        private void button22_Click_1(object sender, EventArgs e)
        {
            ReadDevelopmentTest();
        }

        private void button20_Click(object sender, EventArgs e)
        {
            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            if (!m_DebugRight)
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("没有修改权限", "提示");
                else
                    MessageBox.Show("No permission to modify", "TIPS");
                return;
            }
            if (textBox50.Text == "")
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("设置值不能为空", "提示");
                else
                    MessageBox.Show("Setting value cannot be empty", "TIPS");
                return;
            }

            ushort[] registerhold = new ushort[1];

           
            int value = Convert.ToUInt16(Convert.ToSingle(textBox50.Text));
            if (value < 0)
                value = 65536 + value;
            registerhold[0] = (ushort)value;

            bool bhold = ModbusRtu.SendFc16(m_iDeviceAddr, 6007, 1, registerhold);//电池节数

            if (bhold)
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("设置成功", "提示");
                else
                    MessageBox.Show("Setting successfully", "TIPS");
                 ReadDevelopmentTest();
            }
            else
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("设置失败", "提示");
                else
                    MessageBox.Show("Setting failed", "TIPS");
            }
        }


        private void button42_Click(object sender, EventArgs e)//控制字、产品重启
        {
            if (!m_isPortOpen)
            {
                MessageBox.Show("串口未打开", "提示");
                return;
            }
            ushort[] registerhold = new ushort[1] { 0x5A5A };
            ModbusRtu.SendFc6(m_iDeviceAddr, 2304, 1, registerhold);
            MessageBox.Show("产品重启成功");//无返回
        }

        private void button43_Click(object sender, EventArgs e)//控制字、恢复出厂设置
        {
            if (!m_isPortOpen)
            {
                MessageBox.Show("串口未打开", "提示");
                return;
            }
            ushort[] registerhold = new ushort[1] { 0x5A5A };
            ModbusRtu.SendFc6(m_iDeviceAddr, 2305, 1, registerhold);
            MessageBox.Show("恢复出厂设置成功");//无返回
        }

        //手写指令发送功能
        private void button45_Click(object sender, EventArgs e)//发送指令功能
        {
            if (!m_isPortOpen)
            {
                MessageBox.Show("串口未打开", "提示");
                return;
            }

            label164.Text = (Convert.ToInt32(label164.Text) + 1).ToString();//通讯次数
            List<byte> response = new List<byte>();
            bool hbold = ModbusRtu.SendFcHand(textBox78.Text, ref response);
            Thread.Sleep(35);

            string text = string.Empty;//处理返回的数据
            foreach(byte item in response.ToArray())
            {
                text += item.ToString("X2") + " ";
            }
            textBox79.Text += (text + "\r\n");
            if (hbold)
            {
                label165.Text = (Convert.ToUInt32(label165.Text) + 1).ToString();
            }
            
        }

        static public void Messagesw(string message)
        {
            MessageBox.Show(message);
        }

        private void button46_Click(object sender, EventArgs e)//清空接收数据
        {
            textBox79.Text = string.Empty;
        }



        private bool isAlarmIsExist(string strErrorDesc)
        {
            for (int i = 0; i < listView8.Items.Count; i++)
            {
                string strDesc = listView8.Items[i].SubItems[3].Text;
                if (strDesc == strErrorDesc)
                    return true;
            }

            return false;
        }
        private void isClearAlarmInfo(string strErrorDesc)
        {
            bool isFind = false;
            int index = 0;
            for (int i = 0; i < listView8.Items.Count; i++)
            {
                string strDesc = listView8.Items[i].SubItems[3].Text;
                if (strDesc == strErrorDesc)
                {        
                    isFind = true;
                    index = i;
                    /////////////////////插入数据库
                    string strTime=listView8.Items[i].SubItems[1].Text;
                    string strHexValue=listView8.Items[i].SubItems[2].Text;
                    string strDescHist=listView8.Items[i].SubItems[3].Text;
                    InsertToResultMdb(strTime, strHexValue, strDescHist);
                    listView8.Items.RemoveAt(i);
                    //////////////////////

                }
                if (isFind)
                {
                    if ((i == listView8.Items.Count)&&i>0)
                    {
                        i = i - 1;
                    }
                    if (listView8.Items.Count > 0)
                    {
                        listView8.Items[i].SubItems[0].Text = (i + 1).ToString();
                    }
                }
            }

        }
        private void InsertErrorResult(string ErrorDesc, int index, int value)
        {
            string strHex = Convert.ToString(value, 16);
            string strTime = System.DateTime.Now.ToString();

            if (isAlarmIsExist(ErrorDesc)) return;

            if (listView8.Items.Count < index + 1)
            {

                ListViewItem OptionItem = new ListViewItem((index + 1).ToString());
                OptionItem.SubItems.Add(strTime);//
                OptionItem.SubItems.Add(strHex);//
                OptionItem.SubItems.Add(ErrorDesc);//
                listView8.Items.Add(OptionItem);//执行添加操作*/
            }
            else
            {
                listView8.Items[index].SubItems[2].Text = Convert.ToString(value, 16);
                listView8.Items[index].SubItems[3].Text = ErrorDesc;

            }
        }
        private void ClearListFun(int ListID)
        {
            if (ListID == 3)
            {
                listView8.Items.Clear();
            }
           
            
            this.Update();
        }
        private void ShowCurrentAlarmInfo()//读当前故障
        {
            isRunning6 = true;
            ushort[] registerhold = new ushort[106];
            try
            {
                //float value = 0;
                bool bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 1000, 106, ref registerhold);//
                //int index = 0;

                if (bhold)
                {

                    Invoke(new ShowDataToControlText(ShowAlarmInfoToText), new object[] { registerhold });

                }
                else
                {
                    Invoke(new ShowMonthListView(ClearListFun), new object[] { 3 });
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            isRunning6 = false;

        }
        private void ShowAlarmInfoToText(ushort[] registerhold)
        {
            int index = 0;
            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            for (int i = 0; i < 106; i++)
            {
               // if (i == 3 && i == 5 && i == 14 && i == 22 && i == 30 && i == 38 && i == 46)
                //    continue;

                if (i == 0)
                {
                  //  ReadSystemError1(registerhold[i], ref index);
                    // index++;
                }
                else if (i == 1)
                {
                 //   ReadSystemError2(registerhold[i], ref  index);
                    // index++;
                }
                else if (i == 2)
                {
                    ReadSystemError3(registerhold[i], ref  index);
                    // index++;
                }
                else if (i == 3)
                {
                    ReadSystemError4(registerhold[i], ref  index);
                    // index++;
                }
                else if (i == 4)
                {
                    if (strLang == "ChineseSimplified")
                    Read_Multi_Errorinfo(registerhold, i, ref index,"电池内阻测试仪通讯故障状态报警");
                    else
                        Read_Multi_Errorinfo(registerhold, i, ref index, "Battery internal resistance tester communication fault status alarm");
                    //return;
                }
                else if (i == 12)
                {
                    if (strLang == "ChineseSimplified")
                    Read_Multi_Errorinfo(registerhold, i, ref index, "电池内阻测试仪自身故障状态报警寄存器");
                    else
                        Read_Multi_Errorinfo(registerhold, i, ref index, "Battery internal resistance tester self fault status alarm register");
                }
                else if (i == 20)
                {
                    if (strLang == "ChineseSimplified")
                    Read_Multi_Errorinfo(registerhold, i, ref index, "电池过压故障");
                    else
                        Read_Multi_Errorinfo(registerhold, i, ref index, "Battery overvoltage fault");
                }
                else if (i == 31)
                {
                    if (strLang == "ChineseSimplified")
                    Read_Multi_Errorinfo(registerhold, i, ref index, "电池欠压故障寄存器");  
                    else
                        Read_Multi_Errorinfo(registerhold, i, ref index, "Battery undervoltage fault register"); 
                }
                else if (i == 42)
                {
                    if (strLang == "ChineseSimplified")
                        Read_Multi_Errorinfo(registerhold, i, ref index, "电池过温故障");
                    else
                        Read_Multi_Errorinfo(registerhold, i, ref index, "Battery over temperature fault"); 

                }
                else if (i == 53)
                {
                    if (strLang == "ChineseSimplified")
                        Read_Multi_Errorinfo(registerhold, i, ref index, "电池内阻过大故障");
                    else
                        Read_Multi_Errorinfo(registerhold, i, ref index, "Excessive internal resistance of battery"); 
                }
                else if (i == 64)
                {
                    if (strLang == "ChineseSimplified")
                        Read_Multi_Errorinfo(registerhold, i, ref index, "电池电压高于平均值故障");
                    else
                        Read_Multi_Errorinfo(registerhold, i, ref index, "Battery voltage above average fault"); 
                }
                else if (i == 75)
                {
                    if (strLang == "ChineseSimplified")
                        Read_Multi_Errorinfo(registerhold, i, ref index, "电池电压低于平均值故障");
                    else
                        Read_Multi_Errorinfo(registerhold, i, ref index, "Battery voltage below average fault"); 
                }
                else if (i == 86)
                {
                    if (strLang == "ChineseSimplified")
                        Read_Multi_Errorinfo(registerhold, i, ref index, "电池内阻高于平均值故障");
                    else
                        Read_Multi_Errorinfo(registerhold, i, ref index, "Battery internal resistance above average fault"); 
                }
                else if (i == 97)
                {
                    if (strLang == "ChineseSimplified")
                        Read_Multi_Errorinfo(registerhold, i, ref index, "电池容量过低报警");
                    else
                        Read_Multi_Errorinfo(registerhold, i, ref index, "Low battery capacity alarm"); 
                }
                else if (i==105) //A段出线电流过流故障
                {
                    ReadSystemError5(registerhold[i], ref  index);
                    // index++;
                }
                
                //ReadSystemError1(int index = 0;
            }
        }
        private void ReadSystemError1(ushort uValue, ref int index)
        {
            int temp = 0;
            string strDesc = "";
            for (int i = 0; i < 16; i++)
            {
                temp = (uValue >> i) & 1;
                if (i == 0 && temp == 1)
                {                 
                    strDesc = "总电压过压报警使能";
                    Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                    index++;
                }
                else if (i == 1 && temp == 1)
                {
                    strDesc = "总电压欠压报警使能";
                    Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                    index++;
                }
                else if (i == 2 && temp == 1)
                {
                    strDesc = "电池组放电电流过流报警使";
                    Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                    index++;
                }
                else if (i == 3 && temp == 1)
                {
                    strDesc = "电池组充电电流过流报警使能";
                    Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                    index++;
                }
                else if (i == 4 && temp == 1)
                {
                    strDesc = "环境温度报警使能1";
                    Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                    index++;
                }
                else if (i == 5 && temp == 1)
                {
                    strDesc = "环境温度报警使能2";
                    Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                    index++;
                }
                else if (i == 6 && temp == 1)
                {
                    strDesc = "单节电池过压报警总使能";
                    Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                    index++;
                }
                else if (i == 7 && temp == 1)
                {
                    strDesc = "单节电池欠压报警总使能";
                    Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                    index++;
                }
                else if (i == 8 && temp == 1)
                {
                    strDesc = "单节电池温度过温报警使能";
                    Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                    index++;
                }
                else if (i == 9 && temp == 1)
                {
                    strDesc = "单节电池内阻过高报警使能";
                    Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                    index++;

                }
                else if (i == 10 && temp == 1)
                {
                    strDesc = "单节电池电压高于平均值报警使能";
                    Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                    index++;
                }
                else if (i == 11 && temp == 1)
                {
                    strDesc = "单节电池电压低于平均值报警使能";
                    Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                    index++;
                }
                else if (i == 12 && temp == 1)
                {
                    strDesc = "单节电池内阻高于平均值报警使能";
                    Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                    index++;
                }
                else if (i == 13 && temp == 1)
                {
                    strDesc = "电池内阻测试仪通讯故障报警使能";
                    Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                    index++;
                }
                else if (i == 14 && temp == 1)
                {
                    strDesc = "电流传感器通讯故障报警使能";
                    Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                    index++;
                }
                else if (i == 15 && temp == 1)
                {
                    strDesc = "电池内阻测试仪自身故障使能";
                    Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                    index++;
                }

            }
        }
        private void ReadSystemError2(ushort uValue, ref int index)
        {
            int temp = 0;
            string strDesc = "";
            for (int i = 0; i < 4; i++)
            {
                temp = (uValue >> i) & 1;
                if (i == 0 && temp == 1)
                {
                    strDesc = "电池容量(AH)过低报警";
                    Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                    index++;
                }
                else if (i == 1 && temp == 1)
                {
                  //  strDesc = "总电压欠压报警使能";
                  //  Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                   // index++;
                }
                else if (i == 2 && temp == 1)
                {
                    strDesc = "电压变送器BAT6.1_TV通讯故障报警使能";
                    Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                    index++;
                }
                else if (i == 3 && temp == 1)
                {
                    strDesc = "电池组热失控报警使能";
                    Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                    index++;
                }
               

            }
        }
        private void ReadSystemError3(ushort uValue, ref int index)
        {
            int temp = 0;
            string strDesc = "";
            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            for (int i = 0; i < 16; i++)
            {
                temp = (uValue >> i) & 1;
                if (i == 0)
                {
                    if (strLang == "ChineseSimplified")
                    strDesc = "总电压过压报警状态";
                    else
                        strDesc = "Total voltage overvoltage alarm status";
                    if (temp == 1)
                    {
                        Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                        index++;
                    }
                    else
                    {
                        isClearAlarmInfo(strDesc);
                    }
                }
                else if (i == 1)
                {
          
                    if (strLang == "ChineseSimplified")
                        strDesc = "总电压欠压报警状态";
                    else
                        strDesc = "Total voltage undervoltage alarm status";
                    if (temp == 1)
                    {
                        Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                        index++;
                    }
                    else
                    {
                        isClearAlarmInfo(strDesc);
                    }
                }
                else if (i == 2)
                {
     
                    if (strLang == "ChineseSimplified")
                        strDesc = "电池组放电电流过流报警状";
                    else
                        strDesc = "Battery pack discharge current overcurrent alarm";
                    if (temp == 1)
                    {
                        Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                        index++;
                    }
                    else
                    {
                        isClearAlarmInfo(strDesc);
                    }
                }
                else if (i == 3 )
                {
      
                    if (strLang == "ChineseSimplified")
                        strDesc = "电池组充电电流过流报警状态";
                    else
                        strDesc = "Battery pack charging current overcurrent alarm status";
                    if (temp == 1)
                    {
                        Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                        index++;
                    }
                    else
                    {
                        isClearAlarmInfo(strDesc);
                    }
                }
                else if (i == 4)
                {
                    if (strLang == "ChineseSimplified")
                        strDesc = "环境温度1报警状态";
                    else
                        strDesc = "Ambient temperature 1 alarm status";
                    if (temp == 1)
                    {
                        Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                        index++;
                    }
                    else
                    {
                        isClearAlarmInfo(strDesc);
                    }
                }
                else if (i == 5)
                {
    
                    if (strLang == "ChineseSimplified")
                        strDesc = "环境温度2报警状态";
                    else
                        strDesc = "Ambient temperature 2 alarm status";
                    if (temp == 1)
                    {
                        Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                        index++;
                    }
                    else
                    {
                        isClearAlarmInfo(strDesc);
                    }
                }
                else if (i == 6)
                {
                    if (strLang == "ChineseSimplified")
                        strDesc = "单节电池过压报警总状态";
                    else
                        strDesc = "General status of single battery overvoltage alarm";
                    if (temp == 1)
                    {
                        Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                        index++;
                    }
                    else
                    {
                        isClearAlarmInfo(strDesc);
                    }
                }
                else if (i == 7)
                {
                    if (strLang == "ChineseSimplified")
                        strDesc = "单节电池欠压报警总状态";
                    else
                        strDesc = "General status of single battery undervoltage alarm";
                    if (temp == 1)
                    {
                        Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                        index++;
                    }
                    else
                    {
                        isClearAlarmInfo(strDesc);
                    }
                }
                else if (i == 8)
                {
                    if (strLang == "ChineseSimplified")
                        strDesc = "单节电池温度过温报警总状态";
                    else
                        strDesc = "General status of over temperature alarm of single battery";
                    if (temp == 1)
                    {
                        Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                        index++;
                    }
                    else
                    {
                        isClearAlarmInfo(strDesc);
                    }
                }
                else if (i == 9)
                {
                    if (strLang == "ChineseSimplified")
                        strDesc = "单节电池内阻过高报警总状态";
                    else
                        strDesc = "General STAT of high resistance alarm of single battery";
                    if (temp == 1)
                    {
                        Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                        index++;
                    }
                    else
                    {
                        isClearAlarmInfo(strDesc);
                    }

                }
                else if (i == 10)
                {
                    if (strLang == "ChineseSimplified")
                        strDesc = "单节电池电压高于平均值报警总状态";
                    else
                        strDesc = "General ALM STAT of single BAT Volt higher than average value";
                    if (temp == 1)
                    {
                        Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                        index++;
                    }
                    else
                    {
                        isClearAlarmInfo(strDesc);
                    }
                }
                else if (i == 11)
                {
                    if (strLang == "ChineseSimplified")
                        strDesc = "单节电池电压低于平均值报警总状态";
                    else
                        strDesc = "General ALM STAT of single BAT Volt lower than average value";
                    if (temp == 1)
                    {
                        Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                        index++;
                    }
                    else
                    {
                        isClearAlarmInfo(strDesc);
                    }
                }
                else if (i == 12)
                {
                    if (strLang == "ChineseSimplified")
                        strDesc = "单节电池内阻高于平均值报警总状态";
                    else
                        strDesc = "Overall ALM state when the RES of BAT is higher than the AVG value";
                    if (temp == 1)
                    {
                        Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                        index++;
                    }
                    else
                    {
                        isClearAlarmInfo(strDesc);
                    }
                }
                else if (i == 13)
                {
                    if (strLang == "ChineseSimplified")
                        strDesc = "电池内阻测试仪通讯故障报警总状态";
                    else
                        strDesc = "General status of communication fault alarm of battery internal resistance tester";
                    if (temp == 1)
                    {
                        Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                        index++;
                    }
                    else
                    {
                        isClearAlarmInfo(strDesc);
                    }
                }
                else if (i == 14)
                {
                    if (strLang == "ChineseSimplified")
                        strDesc = "电流传感器通讯故障报警状态";
                    else
                        strDesc = "Current sensor communication fault alarm status";
                    if (temp == 1)
                    {
                        Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                        index++;
                    }
                    else
                    {
                        isClearAlarmInfo(strDesc);
                    }
                }
                else if (i == 15)
                {
                    if (strLang == "ChineseSimplified")
                        strDesc = "电池内阻测试仪自身故障使能";
                    else
                        strDesc = "Battery internal resistance tester self fault enable";
                    if (temp == 1)
                    {
                        Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                        index++;
                    }
                    else
                    {
                        isClearAlarmInfo(strDesc);
                    }
                }

            }
        }
        private void ReadSystemError4(ushort uValue, ref int index)
        {
            int temp = 0;
            string strDesc = "";
            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            for (int i = 0; i < 4; i++)
            {
                temp = (uValue >> i) & 1;
                if (i == 0)
                {
                    if (strLang == "ChineseSimplified")
                    strDesc = "电池组容量过低报警状态";
                    else
                        strDesc = "Low battery pack capacity alarm status";
                    if(temp == 1)
                    {
                       Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                       index++;
                    }
                    else
                    {
                        isClearAlarmInfo(strDesc);
                    }
                }
                else if (i == 1)
                {
             
                    if (strLang == "ChineseSimplified")
                        strDesc = "单节电池容量过低报警状态";
                    else
                        strDesc = "Low single battery capacity alarm status";
                    if(temp == 1)
                    {
                      Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                     index++;
                    }
                    else
                    {
                        isClearAlarmInfo(strDesc);
                    }
                }
                else if (i == 2)
                {
      
                    if (strLang == "ChineseSimplified")
                        strDesc = "电压变送器BAT6.1_VT（或VC）通讯状态";
                    else
                        strDesc = "Voltage transmitter bat6.1_ VT (or VC) communication status";
                    if(temp == 1)
                    {
                    Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                    index++;
                    }
                    else
                    {
                        isClearAlarmInfo(strDesc);
                    }
                }
                else if (i == 3)
                {
          
                    if (strLang == "ChineseSimplified")
                        strDesc = "电池组热失控报警状态";
                    else
                        strDesc = "Battery thermal runaway alarm status";
                    {
                       if(temp == 1)
                        {
                           Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                          index++;
                       }
                       else
                       {
                           isClearAlarmInfo(strDesc);
                       }
                    }
                    
                }
            }
        }
        private void Read_Multi_Errorinfo(ushort[] registerhold, int iArry, ref int index, string strError)
        {
            int temp = 0;
            string strDesc = "";
            string strDesc2 = "";
            int count = 1;
            for (int i = 0; i < 8; i++)
            {
                ushort uValue = registerhold[iArry + i];
                strDesc = strError + (i + 1).ToString();
                for (int j = 0; j < 16; j++)
                { 
                    temp = (uValue >> j) & 1;
                    strDesc2 = "#" + count.ToString() + strDesc;
                    if (temp == 1)
                    {
                        Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc2, index, uValue });
                        index++;
                    }
                    else
                    {
                        isClearAlarmInfo(strDesc2);
                    }
                    count++;
                }

            }
        }
        private void ReadSystemError5(ushort uValue, ref int index)
        {
            int temp = 0;
            string strDesc = "";
            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            for (int i = 0; i < 4; i++)
            {
                temp = (uValue >> i) & 1;
                if (i == 0 && temp == 1)
                {
                    if (strLang == "ChineseSimplified")
                    strDesc = "#199组压模块通讯报警";
                    else
                        strDesc = "#199 group pressure module communication alarm";
                    Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                    index++;
                }
                else if (i == 1 && temp == 1)
                {
                    if (strLang == "ChineseSimplified")
                        strDesc = "#198组压模块通讯报警";
                    else
                        strDesc = "#198 group pressure module communication alarm";
                    Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                    index++;
                }
                else if (i == 2 && temp == 1)
                {                   
                    if (strLang == "ChineseSimplified")
                        strDesc = "#197组压模块通讯报警";
                    else
                        strDesc = "#197 group pressure module communication alarm";
                    Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                    index++;
                }
                else if (i == 3 && temp == 1)
                {             
                    if (strLang == "ChineseSimplified")
                        strDesc = "#196组压模块通讯报警";
                    else
                        strDesc = "#196 group pressure module communication alarm";
                    Invoke(new ShowAlarmInfo(InsertErrorResult), new object[] { strDesc, index, uValue });
                    index++;
                }
            }
        }
        ushort GetValueFromTab(int seniorType,int groupNum)
        {
            ushort value11 = 0xFFFF, value111A = 1;
            //byte b = (byte)~value11;
            value111A = (ushort)(value11 & groupNum);
               
            if (seniorType == 1)
            {
                value111A = (ushort)(value111A | (1 << 15));
            }
            else
            {
                value111A = (ushort)(value111A & ~(1 << 15));
            }

            return value111A;
        }
        bool InsertToResultMdb(string strAlarmTime, string strAlarmValue, string strAlarmDesc)
        {

            string s_sql = "";
            try
            {
                string CREATION_DATE = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
                s_sql = "insert into TestLog(AlarmStartTime,AlarmValue,AlarmDesc)values(#";
                //CString  s_sql = "insert into QISADMIN.QMS_MAKING_MODULE_TITLE(MAKING_MODULE_ID,BAR_CODE,BOM_CODE,PRODUCT_NAME,INTERNAL_TYPE,VERSION,INSPECT_PROC,NOPASS_QTY)values(";
                s_sql += strAlarmTime + "#,'";
                s_sql += strAlarmValue + "','";
                s_sql += strAlarmDesc + "')";

                OleDbCommand cmd = new OleDbCommand(s_sql, conn1);
                try
                {                 
                    cmd.ExecuteNonQuery();                  
                }
                catch (Exception ex)
                {
                    // MessageBox.Show(ex.ToString());
                    //MessageBox.Show(s_sql);
                    return false;
                }

                //InsertToBackupLogMdb(barcode, strResult, strFaultDesc);

            }
            catch (Exception ex)
            {
                //MessageBox.Show("插入数据失败");
                return false;
            }
            //return isOK;
            return true;
        }
        private void GetShinengStatus(int row, int column, ushort value)
        {          
            string strValue = "";
            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            if (strLang == "ChineseSimplified")
            {
                if (value == 1)
                    strValue = "开启";
                else
                    strValue = "关闭";
            }
            else
            {
                if (value == 1)
                    strValue = "Open";
                else
                    strValue = "Closed";
            }

            this.dataGridView2.Rows[row].Cells[column].Value = strValue;      
        }
        private void GetSystemRangeStatus(int row, ushort value)
        {
            
            
                 Language lang = this.CurrentSelectedLanguage;
                 string strLang = lang.ToString();
                 //////////////////////////////获取时间
                
            
            
            string strValue = value.ToString();
            string SeniorType = this.dataGridView2.Rows[row].Cells[3].Value.ToString();
            if (strLang == "ChineseSimplified")
            {
                if (SeniorType == "充放电流传感器")
                    this.dataGridView2.Rows[row].Cells[6].Value = "A";
                else
                    this.dataGridView2.Rows[row].Cells[6].Value = "mA";
            }
            else
            {
                if (SeniorType == "Chg-dischg CUR SEN")
                    this.dataGridView2.Rows[row].Cells[6].Value = "A";
                else
                    this.dataGridView2.Rows[row].Cells[6].Value = "mA";
            }
           

            this.dataGridView2.Rows[row].Cells[5].Value = strValue;
        }
        private void GetSeniorAndGroupStatus(int row1, ushort value)
        {

             Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            //////////////////////////////获取时间
           

            int temp = (value >> 15) & 1;
            
            string strValue1 = "";
            string strValue2 = "";


            if (strLang == "ChineseSimplified")
            {
                if (temp == 0)
                    strValue1 = "充放电流传感器";
                else
                    strValue1 = "浮充电流传感器";
            }
            else           
            {
                if (temp == 0)
                    strValue1 = "Chg-dischg CUR SEN";
                else
                    strValue1 = "Float CUR SEN";
            }

            this.dataGridView2.Rows[row1].Cells[3].Value = strValue1;

            ushort value1 = (ushort)(value & 255);
            if (strLang == "ChineseSimplified")
            {
                if (value1 == 0)
                    strValue2 = "不关联";
                else if (value1 == 1)
                    strValue2 = "第1组";
                else if (value1 == 2)
                    strValue2 = "第2组";
                else if (value1 == 3)
                    strValue2 = "第3组";
                else if (value1 == 4)
                    strValue2 = "第4组";
                else if (value1 == 5)
                    strValue2 = "第5组";
                else if (value1 == 6)
                    strValue2 = "第6组";

              
            }
            else
            {
                if (value1 == 0)
                    strValue2 = "Unassociated";
                else if (value1 == 1)
                    strValue2 = "Group1";
                else if (value1 == 2)
                    strValue2 = "Group2";
                else if (value1 == 3)
                    strValue2 = "Group3";
                else if (value1 == 4)
                    strValue2 = "Group4";
                else if (value1 == 5)
                    strValue2 = "Group5";
                else if (value1 == 6)
                    strValue2 = "Group6";
         
            }

            this.dataGridView2.Rows[row1].Cells[4].Value = strValue2;
        }

        private void button18_Click(object sender, EventArgs e)
        {

            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            if (!m_DebugRight)
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("没有修改权限", "提示");
                else
                    MessageBox.Show("No permission to modify", "TIPS");
                return;
            }
            button18.Enabled = false;
            
            ushort[] registerhold = new ushort[1];

            textBox49.Text = textBox49.Text.Trim();
            registerhold[0] = Convert.ToUInt16(textBox49.Text);


            bool bhold = ModbusRtu.SendFc6(m_iDeviceAddr, 7446, 1, registerhold);//内阻过高报警模式
            if (bhold)
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("设置成功", "提示");
                else
                    MessageBox.Show("Setting successfully", "TIPS");
                //GetParamTestValue();
            }
            else
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("设置失败", "提示");
                else
                    MessageBox.Show("Setting failed", "TIPS");
            }
            button18.Enabled = true;
        }

        private void button19_Click(object sender, EventArgs e)
        {
            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            if (!m_DebugRight)
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("没有修改权限", "提示");
                else
                    MessageBox.Show("No permission to modify", "TIPS");
                return;
            }
            button19.Enabled = false;
            ushort[] registerhold = new ushort[1];
            registerhold[0] = 0xFFFF;
            //registerhold[0] = Convert.ToUInt16(Convert.ToSingle(textBox41.Text) * 1000);//进线过压阈值:
            bool bhold = ModbusRtu.SendFc6(m_iDeviceAddr, 7446, 1, registerhold);//电池节数
            if (bhold)
            {
                if (strLang == "ChineseSimplified")
                MessageBox.Show("设置成功", "提示");
                else
                    MessageBox.Show("Setting successfully", "TIPS");
                //GetParamTestValue();
            }
            else
            {
                if (strLang == "ChineseSimplified")
                MessageBox.Show("设置失败", "提示");
                else
                    MessageBox.Show("Setting failed", "TIPS");
            }
            button19.Enabled = true;
        }

        private void button23_Click(object sender, EventArgs e)
        {
            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            try
            {
                if (!m_isPortOpen)
                {
                    if (strLang == "ChineseSimplified")
                        MessageBox.Show("串口未打开", "提示");
                    else
                        MessageBox.Show("Serial port is not opened", "TIPS");
                    return;
                }

                GetSysConfValue();
                this.Update();
                tabControl1.Update();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void button24_Click(object sender, EventArgs e)
        {
            ReadNeiZuAlarmSet();
        }
        private void InsertErrorHistoryResult(string strStartTime,string strEndTime, string strHex,string ErrorDesc, int index, int value)
        {
            
            if (listView9.Items.Count < index + 1)
            {
                ListViewItem OptionItem = new ListViewItem((index + 1).ToString());
                OptionItem.SubItems.Add(strStartTime);//
                OptionItem.SubItems.Add(strEndTime);//
                OptionItem.SubItems.Add(strHex);//
                OptionItem.SubItems.Add(ErrorDesc);//
                listView9.Items.Add(OptionItem);//执行添加操作*/
            }
            else
            {
                listView9.Items[index].SubItems[1].Text = strStartTime;
                listView9.Items[index].SubItems[2].Text = strEndTime;
                listView9.Items[index].SubItems[3].Text = strHex;
                listView9.Items[index].SubItems[4].Text = ErrorDesc;
            }
        }

        public void ShowAlarmHistoryList(int mode)
        {
            try
            {

                Language lang = this.CurrentSelectedLanguage;
                string strLang = lang.ToString();
                //////////////////////////////获取时间
       
                listView9.Items.Clear();
                string Sql = "";
               // string Sql = "SELECT  * from TestLog order by AlarmStartTime desc";
                if (mode == 1)//周
                {
                    Sql = "SELECT * FROM TestLog WHERE DateDiff('w',[AlarmStartTime],Date())=0 order by AlarmStartTime desc";
                    if (strLang == "ChineseSimplified")
                    label120.Text = "一周内";
                    else
                    label120.Text = "Within one week";
                }
                else if (mode == 2)//当天
                {
                    Sql = "SELECT * FROM TestLog WHERE DateDiff('d',[AlarmStartTime],Date())=0 order by AlarmStartTime desc";
                    if (strLang == "ChineseSimplified")
                    label120.Text = "当天查询";
                    else
                    label120.Text = "Current day query";
                }
                else
                {
                    string strStartTime = dateTimePicker1.Value.ToString();
                    string strEndTime = dateTimePicker2.Value.ToString();
                    Sql = "SELECT * FROM TestLog WHERE  AlarmStartTime>=#" + strStartTime + "# and AlarmStartTime <=#" + strEndTime + "#"+" order by AlarmStartTime desc";
                    if (strLang == "ChineseSimplified")
                    label120.Text = "时间段查询";
                    else
                    label120.Text = "Time period query";
                }


                OleDbCommand cmd = new OleDbCommand(Sql, conn1);

                cmd.CommandText = Sql;
                OleDbDataReader thisReader = cmd.ExecuteReader();
                int i = 1;
                while (thisReader.Read())
                {
                    string StartTime = thisReader["AlarmStartTime"].ToString();
                    string EndTime = thisReader["AlarmEndTime"].ToString();
                    string strHex = thisReader["AlarmValue"].ToString();
                    //string Version = thisReader["Version"].ToString();
                    string strDesc = thisReader["AlarmDesc"].ToString();

                    ListViewItem OptionItem = new ListViewItem(i.ToString());//定义一个listView选择项的实例

                    OptionItem.SubItems.Add(StartTime);//向listView控件中添加文件创建时间列

                    OptionItem.SubItems.Add(EndTime);//向listView控件中添加文件创建时间列

                    OptionItem.SubItems.Add(strHex);//向listView控件中添加文件创建时间列
                    OptionItem.SubItems.Add(strDesc);//向listView控件中添加文件创建时间列
                    // OptionItem.SubItems.Add(Version);//向listView控件中添加文件创建时间列

                    //OptionItem.SubItems.Add(FileType);//向listView控件中添加文件创建时间列

                    listView9.Items.Add(OptionItem);//执行添加操作//添加操作

                    i++;
                }

                thisReader.Close();
                //comboBox1.SelectedIndex = 0;
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());

            }
        }

        private void button25_Click(object sender, EventArgs e)
        {
            ShowAlarmHistoryList(3);
        }

        private void button26_Click(object sender, EventArgs e)
        {
            ShowAlarmHistoryList(1);
        }

        private void button27_Click(object sender, EventArgs e)
        {
            ShowAlarmHistoryList(2);
        }

        private void button28_Click(object sender, EventArgs e)
        {
            GetAlarmStatus();
        }

        private void textBox39_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                if (e.KeyChar == '.') return;

                e.Handled = true;
                // MessageBox.Show("dd");
            }
            else
            {

            }
        }

        private void textBox40_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                if (e.KeyChar == '.') return;

                e.Handled = true;
                // MessageBox.Show("dd");
            }
            else
            {

            }
        }

        private void textBox41_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                if (e.KeyChar == '.') return;

                e.Handled = true;
                // MessageBox.Show("dd");
            }
            else
            {

            }
        }

        private void textBox42_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                if (e.KeyChar == '.') return;

                e.Handled = true;
                // MessageBox.Show("dd");
            }
            else
            {

            }
        }

        private void 中文ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            strLabel6 = label6.Text;
            MultiLanguage.SetDefaultLanguage("zh-CN");
            this.CurrentSelectedLanguage = Language.ChineseSimplified;
            foreach (Form form in Application.OpenForms)
            {
                LoadAll(form);
            }
            ChangeListLange();
            GetDeviceTestModeInfo();
            InsertToSysConfig2();
            ChangeToLabel();
           // ChangedataGridView2Lange();
            MessageBox.Show("必须重启软件", "提示");
            Application.Exit();
        }

        private void 英文ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            strLabel6 = label6.Text;
            MultiLanguage.SetDefaultLanguage("en-US");
            this.CurrentSelectedLanguage = Language.English;
            foreach (Form form in Application.OpenForms)
            {
                LoadAll(form);
            }
            ChangeListLange();
            GetDeviceTestModeInfo();
            InsertToSysConfig2();
            ChangeToLabel();
            MessageBox.Show("Need Restart now", "TIPS");
            Application.Exit();
          //  ChangedataGridView2Lange();
        }
        private void LoadAll(Form form)
        {
            if (form.Name == "Form1")
            {
                MultiLanguage.LoadLanguage(form, typeof(Form1));
            }
            //如果还有别的窗体，这里要完善一下
        }




        //KO模块

        private void recover_KOCheckBoxes()//KO模块报交警设置清零
        {
            List<CheckBox> checkBoxes = new List<CheckBox> {
                checkBox_bit0,checkBox_bit1,checkBox_bit2,checkBox_bit3,checkBox_bit4,checkBox_bit5,checkBox_bit6,
                checkBox_bit7,checkBox_bit8,checkBox_bit9,checkBox_bit10,checkBox_bit11,checkBox_bit12,checkBox_bit13 };
            foreach (CheckBox checkBox in checkBoxes)
            {
                checkBox.Checked = false;
            }
        }

        private void radioButton_relay1_CheckedChanged(object sender, EventArgs e)//KO模块继电器1
        {
            //先清空设置
            recover_KOCheckBoxes();
            //设置选择框的内容
            button_KOupdate_Click(sender, e);
        }

        private void radioButton_relay2_CheckedChanged(object sender, EventArgs e)//KO模块继电器2
        {
            //先清空设置
            recover_KOCheckBoxes();
            //设置选择框的内容
            button_KOupdate_Click(sender, e);
        }

        private void radioButton_relay3_CheckedChanged(object sender, EventArgs e)//KO模块继电器3
        {
            //清空设置,默认值0
            recover_KOCheckBoxes();
            //设置选择框的内容
            button_KOupdate_Click(sender, e);
        }

        private void radioButton_relay4_CheckedChanged(object sender, EventArgs e)//KO模块继电器4
        {
            //清空设置,默认值0
            recover_KOCheckBoxes();
            //设置选择框的内容
            button_KOupdate_Click(sender, e);
        }

        private void button_KOupdate_Click(object sender, EventArgs e)//刷新当前选择的继电器
        {
            //1.读取的地址
            ushort start = 2095;
            Dictionary<RadioButton, ushort> keyValuePairs = new Dictionary<RadioButton, ushort>();
            keyValuePairs[radioButton_relay1] = 2095;
            keyValuePairs[radioButton_relay2] = 2096;
            keyValuePairs[radioButton_relay3] = 2097;
            keyValuePairs[radioButton_relay4] = 2098;
            foreach (RadioButton radioButton in keyValuePairs.Keys)
            {
                if (radioButton.Checked == true)//查到选择的寄存器后可以退出循环  
                {
                    start = keyValuePairs[radioButton];
                    break;
                }
            }

            //2.发送指令06
            ushort[] registerhold = new ushort[1];
            bool bhold = ModbusRtu.SendFc3(m_iDeviceAddr, start, 1, ref registerhold);//电池节数
            if (!bhold) MessageBox.Show("获取失败", "提示");

            //3.处理数据，并选中选择框的内容,十进制
            ushort value = registerhold[0];

            List<CheckBox> checkBoxes = new List<CheckBox> {
                checkBox_bit0,checkBox_bit1,checkBox_bit2,checkBox_bit3,checkBox_bit4,checkBox_bit5,checkBox_bit6,
                checkBox_bit7,checkBox_bit8,checkBox_bit9,checkBox_bit10,checkBox_bit11,checkBox_bit12,checkBox_bit13 };
            for (int i = 0; i < checkBoxes.Count; i++)
            {
                if (((value & (1 << i)) >> i) == 1) checkBoxes[i].Checked = true;
                else checkBoxes[i].Checked = false;

            }
        }

        private void button_KO_Click(object sender, EventArgs e)//KO模块写入设置
        {
            //1.发送的数据。发送的数据区内容 06单个寄存器写
            ushort[] registerhold = new ushort[1];
            ushort value = 0x0000;
            //处理选中的选择框的内容
            List<CheckBox> checkBoxes = new List<CheckBox> {
                checkBox_bit0,checkBox_bit1,checkBox_bit2,checkBox_bit3,checkBox_bit4,checkBox_bit5,checkBox_bit6,
                checkBox_bit7,checkBox_bit8,checkBox_bit9,checkBox_bit10,checkBox_bit11,checkBox_bit12,checkBox_bit13 };
            foreach (CheckBox checkBox in checkBoxes)
            {
                //true是1，false是0
                if (checkBox.Checked == true)
                {
                    value = (ushort)(value | (1 << checkBoxes.IndexOf(checkBox)));
                }
                else
                {
                    value = (ushort)(value & ~(1 << checkBoxes.IndexOf(checkBox)));
                }
            }
            registerhold[0] = value;

            //2.发送的地址
            ushort start = 2095;
            Dictionary<RadioButton, ushort> keyValuePairs = new Dictionary<RadioButton, ushort>();
            keyValuePairs[radioButton_relay1] = 2095;
            keyValuePairs[radioButton_relay2] = 2096;
            keyValuePairs[radioButton_relay3] = 2097;
            keyValuePairs[radioButton_relay4] = 2098;
            foreach (RadioButton radioButton in keyValuePairs.Keys)
            {
                if (radioButton.Checked == true)//查到选择的寄存器后可以退出循环  
                {
                    start = keyValuePairs[radioButton];
                    break;
                }
            }

            //3.发送指令06
            bool bhold = ModbusRtu.SendFc6(m_iDeviceAddr, start, 1, registerhold);

            if (bhold) MessageBox.Show("设置成功", "提示");
            else MessageBox.Show("设置失败", "提示");
        }

        //零漂置零
        private void button35_Click(object sender, EventArgs e)//读取当前置零值
        {
            ushort[] registerhold = new ushort[1];
            bool bhold = ModbusRtu.SendFc3(m_iDeviceAddr, 2094, 1, ref registerhold);
            if (bhold)
                label_currentZeroing.Text = registerhold[0].ToString();
        }

        private void button38_Click(object sender, EventArgs e)//设置置零值
        {
            label_Statue_Zeroing.Text = General;
            if (System.Text.RegularExpressions.Regex.IsMatch(textBox_to_Zeroing.Text,@"^[0-9]*$") & Convert.ToInt16 (textBox_to_Zeroing.Text)>= 0 && Convert.ToInt16(textBox_to_Zeroing.Text) <= 100)
            {
                ushort[] registerhold = new ushort[1];
                registerhold[0] = Convert.ToUInt16(textBox_to_Zeroing.Text);
                bool bhold = ModbusRtu.SendFc6(m_iDeviceAddr, 2094, 1, registerhold);
                label_Statue_Zeroing.Text = bhold ? Success : Failure;  
            }else
                MessageBox.Show("请检查输入格式是否正确", "提示");
        }




        //12单体内阻页面

        private void setResistance(string neizu, byte index)//单体内阻表格数值
        {
            if (dataGridView3.Rows.Count <= index + 1)
            {
                DataGridViewRow row = new DataGridViewRow();//0
                row.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                row.CreateCells(dataGridView3);
                row.Cells[0].Value = (index + 1).ToString();
                row.Cells[1].Value = neizu;
                row.Cells[2].Value = string.Empty;
                row.Cells[3].Value = string.Empty;
                row.Cells[4] = new DataGridViewButtonCell();
                row.Cells[4].Value = "写入";
                row.Cells[5].Value = General;

                dataGridView3.Rows.Add(row);
            }
            else
            {
                dataGridView3.Rows[index].Cells[1].Value = neizu;
                dataGridView3.Rows[index].Cells[2].Value = string.Empty;
                dataGridView3.Rows[index].Cells[3].Value = string.Empty;
                dataGridView3.Rows[index].Cells[5].Value = General;
            }
        }

        private void updateCoe(float original, int rowid)//系数计算显示,用目标阻值/原始阻值
        {
            short coe = (short)(Convert.ToDouble(dataGridView3.Rows[rowid].Cells[2].Value) / original * 100);//计算修正阻值=目标阻值/
            //修正阻值在1-255之间，要给出提示
            if (coe > 255 | coe < 1)
            {
                dataGridView3.Rows[rowid].Cells[3].Style.ForeColor = Color.Red;
            }   
            else if (dataGridView3.Rows[rowid].Cells[3].Style.ForeColor == Color.Red)
            {
                dataGridView3.Rows[rowid].Cells[3].Style.ForeColor = Color.Black;
            }
            dataGridView3.Rows[rowid].Cells[3].Value = coe.ToString();
            dataGridView3.Rows[rowid].Cells[5].Value = General;
        }

        private void button41_Click(object sender, EventArgs e)//实时读取数据停止
        {
            if(thread_poll.IsAlive) thread_poll.Abort();
            button3.Text = "开始测试";
            button41.Enabled = false;
        }
       
        private void button33_Click(object sender, EventArgs e)//读取实际内阻和原始阻值
        {
            if (dataGridView3.RowCount > 1)
            {
                button33.Enabled = false;//防止连续点击
                bool bRet = false;
                ushort icount = (ushort)(dataGridView3.RowCount - 1);//电池个数
                Thread.Sleep(800 + icount * 35);//强制停留，这里设置时间间隔是防止，修改系数还没参与运算，用户就又点击读取阻值,35ms时处理一个寄存器的时间

                ushort registers = (ushort)((icount + 1) / 2);                                      //存修正系数的寄存器个数
                ushort neiZuRegisters = (ushort)(icount*3);

                //读取的实际的阻值=原始阻值*系数
                ushort[] registerhold1 = new ushort[3 * 40];                                         //读取实际缓冲区                                       
                ushort[] internalResistance= new ushort[3 * icount];                                 //真正存内阻的缓冲区
                reviseResistance = new ushort[registers];                                            //读取修正系数，存放到全局变量reviseResistance里面

                if (icount <= 40)
                {
                    
                    bRet=ModbusRtu.SendFc3(m_iDeviceAddr, 50, neiZuRegisters, ref internalResistance);      //读取的实际内阻值
                    if (bRet == false)
                        MessageBox.Show("error in modbus1");
                }
                if (icount > 40 && icount <= 80)
                {
                    bRet=ModbusRtu.SendFc3(m_iDeviceAddr, 50, 120, ref registerhold1);      //读取的实际内阻值
                    if (bRet == false)
                        MessageBox.Show("error in modbus2");
                    Array.Copy(registerhold1, 0, internalResistance, 0, 120);

                    bRet =ModbusRtu.SendFc3(m_iDeviceAddr, 170, (ushort)(icount*3-120), ref registerhold1);
                    if (bRet == false)
                        MessageBox.Show("error in modbus3");
                    Array.Copy(registerhold1, 0, internalResistance, 120, icount * 3 - 120);
                }
                if (icount > 80 && icount <= 120)
                {
                    bRet=ModbusRtu.SendFc3(m_iDeviceAddr, 50, 120, ref registerhold1);      //读取的实际内阻值
                    if (bRet == false)
                        MessageBox.Show("error in modbus4");
                    Array.Copy(registerhold1, 0, internalResistance, 0, 120);

                    bRet= ModbusRtu.SendFc3(m_iDeviceAddr, 170, 120, ref registerhold1);
                    if (bRet == false)
                        MessageBox.Show("error in modbus5");
                    Array.Copy(registerhold1, 0, internalResistance, 120, 120);

                    bRet=ModbusRtu.SendFc3(m_iDeviceAddr, 290, (ushort)(icount * 3 - 240), ref registerhold1);
                    if (bRet == false)
                        MessageBox.Show("error in modbus6");
                    Array.Copy(registerhold1, 0, internalResistance, 240, (ushort)(icount * 3 - 240));
                }


                //读取修正系数，备份，等待后面写默认系数后用此系数还原
                Thread.Sleep(icount * 35);
                bRet=ModbusRtu.SendFc3(m_iDeviceAddr, 2308, registers, ref reviseResistance);
                if (bRet == false)
                    MessageBox.Show("error in modbus 7");

                //刷新DataGridView实际内阻列
                Thread.Sleep(icount * 35);
                for (byte i = 0; i < icount; ++i)
                {   
                    dataGridView3.Rows[i].Cells[1].Value = ((float)internalResistance[3 * i + 2] / 1000).ToString("0.000"); //设置读出的实际内阻
                    dataGridView3.Rows[i].Cells[3].Value = string.Empty;
                    dataGridView3.Rows[i].Cells[5].Value = General;
                }


                //设置修正系数 6464
                ushort[] registerhold = new ushort[registers];
                for (ushort i = 0; i < registers; ++i)
                {
                    registerhold[i] = 0x6464;
                }
                bool hbold= ModbusRtu.SendFc16(m_iDeviceAddr, 2308, registers, registerhold);//64写，恢复到默认修正系数阻值
                if (hbold == false)
                    MessageBox.Show("error in modbus 8"+ModbusRtu.modbusStatus);
                //时间要间隔久一点
                Thread.Sleep(2000 + icount * 35);


                //读初始电池组原始阻值
                if (icount <= 40)
                {
                    bRet=ModbusRtu.SendFc3(m_iDeviceAddr, 50, neiZuRegisters, ref internalResistance);
                    if (bRet == false)
                        MessageBox.Show("error in modbus 9");
                }
                if (icount > 40 && icount <= 80)
                {
                    ModbusRtu.SendFc3(m_iDeviceAddr, 50, 120, ref registerhold1);      //读取的实际内阻值
                    if (bRet == false)
                        MessageBox.Show("error in modbus 10");
                    Array.Copy(registerhold1, 0, internalResistance, 0, 120);
                    ModbusRtu.SendFc3(m_iDeviceAddr, 170, (ushort)(icount * 3 - 120), ref registerhold1);
                    if (bRet == false)
                        MessageBox.Show("error in modbus 11");
                    Array.Copy(registerhold1, 0, internalResistance, 120, icount * 3 - 120);
                }
                if (icount > 80 && icount <= 120)
                {
                    ModbusRtu.SendFc3(m_iDeviceAddr, 50, 120, ref registerhold1);      //读取的实际内阻值
                    if (bRet == false)
                        MessageBox.Show("error in modbus 12");
                    Array.Copy(registerhold1, 0, internalResistance, 0, 120);

                    ModbusRtu.SendFc3(m_iDeviceAddr, 170, 120, ref registerhold1);
                    if (bRet == false)
                        MessageBox.Show("error in modbus 13");
                    Array.Copy(registerhold1, 0, internalResistance, 120, 120);
                    ModbusRtu.SendFc3(m_iDeviceAddr, 290, (ushort)(icount * 3 - 240), ref registerhold1);
                    if (bRet == false)
                        MessageBox.Show("error in modbus 14");
                    Array.Copy(registerhold1, 0, internalResistance, 240, (ushort)(icount * 3 - 240));
                }

                //存储所有的原始阻值
                originalResistance = new ushort[icount];
                for (int i = 0; i < icount; ++i)
                {
                    originalResistance[i] = internalResistance[3 * i + 2];
                }

                //写入先前读取用以备份的系数，恢复实际阻值
                Thread.Sleep(20);
                bRet=ModbusRtu.SendFc16(m_iDeviceAddr, 2308, registers, reviseResistance);//写

                if (bRet == false)
                    MessageBox.Show("error in modbus 15" + ModbusRtu.modbusStatus);

                button33.Enabled = true;
            }
        }

        private void setOriginal()//保存电池组阻值
        {
            int icount = dataGridView3.RowCount - 1;//电池个数
            ushort[] registerhold3 = new ushort[3 * icount];//读取改写后的实际的阻值
            ModbusRtu.SendFc3(m_iDeviceAddr, 50, (ushort)(3 * icount), ref registerhold3);//有个问题就是，可能64 64还没写进去就读，那只能时原来的实际阻值，而不是改变后的
            for (int i = 0; i < icount; ++i)
            {
                originalResistance[i] = registerhold3[3 * i + 2];
            }
        }

        private bool judge_ArmResistanceisLost()//判断如果目标阻值缺失
        {
            for(int i = 0; i < dataGridView3.RowCount - 1; ++i)
            {
                if (dataGridView3.Rows[i].Cells[2].Value.ToString() == string.Empty)
                {
                    return false;
                }
            }
            return true;
        }

        private void button31_Click(object sender, EventArgs e)//系数刷新按钮，根据读取的数据和设置的阻值计算，并清空状态
        {
            //判断如果目标阻值缺失，则不能点击
            if (!judge_ArmResistanceisLost())
            {
                MessageBox.Show("目标阻值存在缺失，请检查");
                return;
            }

            button31.Enabled = false;//防止连续点击
            //获取原始阻值.和获取阻值按钮效果一致
            button33_Click(null, e);
            //计算差值
            int icount = dataGridView3.RowCount - 1;
            if (icount > 0)
            {
                float ori;
                for (int index = 0; index < icount; index++)//也可以循环调用 dataGridView3_CellEndEdit的逻辑，有点麻烦
                {
                    ori = (float)(originalResistance[index]) / 1000;

                    updateCoe(ori, index);//传入原始阻值，计算系数
                }
            }
            button31.Enabled = true;
        }

        private void button29_Click(object sender, EventArgs e)//写入设定的目标阻值
        {
            double result;
            if(double.TryParse(textBox_StdCoe.Text,out result)) //(System.Text.RegularExpressions.Regex.IsMatch(textBox_StdCoe.Text, @"^[0-9].$"))
            {
                button29.Enabled = false;
                for (int index = 0; index < dataGridView3.RowCount - 1; index++)
                {
                    dataGridView3.Rows[index].Cells[2].Value = textBox_StdCoe.Text;
                }
                button29.Enabled = true;
            }
            else MessageBox.Show("请检查输入格式是否正确", "提示");

        }

        private void dataGridView3_CellEndEdit(object sender, DataGridViewCellEventArgs e)//手动改写修改的目标阻值，系数改变
        {
            if (e.ColumnIndex == 2 & e.RowIndex < dataGridView3.RowCount - 1)
            {
                if (originalResistance == null | reviseResistance == null )
                {

                    MessageBox.Show("请先点击“获取电阻”按钮，获取原始阻值和修正系数");
                }
                else if ( originalResistance.Length != dataGridView3.RowCount - 1 |  reviseResistance.Length != dataGridView3.RowCount / 2)
                {
                    MessageBox.Show("请先点击“获取电阻”按钮，获取原始阻值和修正系数");
                }
                else
                {
                    //获取原始数据
                    float ori = (float)(originalResistance[e.RowIndex]) / 1000;     //在低位

                    updateCoe(ori, e.RowIndex);
                }
            }
        }

        private bool judge_ReviseResistanceisLost()//判断修正系数是否有缺失，存在缺失就不能写入;检验系数是否合理，不合理也不能写入
        {
            for (int index = 0; index < dataGridView3.RowCount - 1; ++index)
            {
                if (dataGridView3.Rows[index].Cells[3].Value.ToString()==string.Empty)
                {
                    Console.WriteLine(index.ToString() + "," + dataGridView3.Rows[index].Cells[3].Value.ToString());
                    return false;
                }

            }
            return true;
        }
        //判断修正的温差是否为空
        private bool judge_ReviseResistanceisLost2()//判断修正系数是否有缺失，存在缺失就不能写入;检验系数是否合理，不合理也不能写入
        {
            for (int index = 0; index < dataGridView4.RowCount - 1; ++index)
            {
                if (dataGridView4.Rows[index].Cells[3].Value.ToString() == string.Empty)
                {
                    //Console.WriteLine(index.ToString() + "," + dataGridView4.Rows[index].Cells[3].Value.ToString());
                    return false;
                }

            }
            return true;
        }

        private bool judge_ReviseResistanceisOutBorder()//判断检验系数是否合理，不合理也不能写入
        {
            for (int index = 0; index < dataGridView3.RowCount - 1; ++index)
            {
                if (dataGridView3.Rows[index].Cells[3].Style.ForeColor == Color.Red)
                {
                    return false;
                }
            }
            return true;
        }

        private void button30_Click(object sender, EventArgs e)//根据系数改变阻值,全部一次写
        {
            if (!m_isPortOpen)
            {
               MessageBox.Show("串口未打开", "提示");
                return;
            }
            //0.警告
            if (!judge_ReviseResistanceisLost())
            {
                MessageBox.Show("修正系数存在缺失值，请检查", "警告");
                return;
            }
            if (!judge_ReviseResistanceisOutBorder())
            {
                MessageBox.Show("所有系数设置必须在1-255之间", "警告");
                return;
            }

            if (dataGridView3.RowCount > 1)
            {
                int icount = dataGridView3.RowCount - 1;//电池个数

                //1.处理数据
                ushort registers = (ushort)((icount + 1) / 2);//寄存器个数
                ushort[] registerhold = new ushort[registers];
                for (int index = 0; index < icount; index++)
                {
                    if (index % 2 == 0)//在低位
                        registerhold[index / 2] = Convert.ToUInt16(dataGridView3.Rows[index].Cells[3].Value);
                    else//在高位
                        registerhold[index / 2] += (ushort)(Convert.ToUInt16(dataGridView3.Rows[index].Cells[3].Value) << 8);
                }
                //如果时奇数个bat，在最后一个寄存器前加上0x64
                if (icount % 2 == 1) registerhold[registers - 1] += 25600;

                //2.发送数据
                bool bhold = ModbusRtu.SendFc16(m_iDeviceAddr, 2308, registers, registerhold);
                Thread.Sleep(2000 + registers * 35);
                if (bhold)
                {
                    for (int index = 0; index < icount; ++index)
                    {
                        dataGridView3.Rows[index].Cells[5].Value = Success;
                        dataGridView3.Rows[index].Cells[5].Style.ForeColor = Color.Green;
                    }
                }
                else
                {
                    for (int index = 0; index < icount; ++index)
                    {
                        dataGridView3.Rows[index].Cells[5].Value = Failure;
                        dataGridView3.Rows[index].Cells[5].Style.ForeColor = Color.Red;
                    }
                }
            }
            else
                MessageBox.Show("请检查是否链接到电池", "提示");

        }

        private void dataGridView3_CellClick(object sender, DataGridViewCellEventArgs e)//点击一个单体的button按钮事件
        {
            if (!m_isPortOpen)
            {
                MessageBox.Show("串口未打开", "提示");
                return;
            }
            Console.WriteLine(e.RowIndex.ToString());
            if (e.ColumnIndex == 4 & e.RowIndex < dataGridView3.RowCount - 1&&e.RowIndex>=0)
            {   
                //警告
                if (dataGridView3.Rows[e.RowIndex].Cells[3].Style.ForeColor == Color.Red)
                {
                    MessageBox.Show("系数设置必须在1-255之间", "警告");
                    return;
                }
                if (dataGridView3.Rows[e.RowIndex].Cells[3].Value.ToString() == string.Empty)
                {
                    MessageBox.Show("存在修正系数缺失", "警告");
                    return;
                }

                //1.处理数据
                ushort start = (ushort)(2308 + e.RowIndex / 2);
                ushort[] registerhold = new ushort[1] { reviseResistance[e.RowIndex / 2] };//从
                if (e.RowIndex % 2 == 0)//在低位
                {
                    registerhold[0] = (ushort)(registerhold[0] & 0xFF00);//保留高位
                    registerhold[0] += Convert.ToUInt16(dataGridView3.Rows[e.RowIndex].Cells[3].Value);
                }
                else//在高位
                {
                    registerhold[0] = (ushort)(registerhold[0] & 0xFF);//保留低位
                    registerhold[0] += (ushort)(Convert.ToUInt16(dataGridView3.Rows[e.RowIndex].Cells[3].Value) << 8);
                }

                //2.发送指令
                bool bhold = ModbusRtu.SendFc6(m_iDeviceAddr, start, 1, registerhold);
                //强制等待35ms，确保用户无时间间隔点击发送按钮仍然可以正确读数
                Thread.Sleep(35);

                //3.反馈
                if (bhold)
                {
                    //修改成功将修正阻值系数进行修改
                    reviseResistance[e.RowIndex / 2] = registerhold[0];

                    dataGridView3.Rows[e.RowIndex].Cells[5].Value = Success;
                    dataGridView3.Rows[e.RowIndex].Cells[5].Style.ForeColor = Color.Green;
                }
                else
                {
                    dataGridView3.Rows[e.RowIndex].Cells[5].Value = Failure;
                    dataGridView3.Rows[e.RowIndex].Cells[5].Style.ForeColor = Color.Red;
                }
            }
        }

        private void button40_Click(object sender, EventArgs e)//恢复电池内阻
        {
            if (!m_isPortOpen)
            {
                MessageBox.Show("串口未打开", "提示");
                return;
            }
            if (dataGridView3.RowCount > 1)
            {
                int icount = dataGridView3.RowCount - 1;//电池个数

                //1.处理数据
                ushort registers = (ushort)((icount + 1) / 2);//寄存器个数
                ushort[] registerhold = new ushort[registers];
                for (int i = 0; i < registers; ++i)
                    registerhold[i] = 25700;
                
                //2.发送数据
                bool bhold = ModbusRtu.SendFc16(m_iDeviceAddr, 2308, registers, registerhold);
                if (bhold)
                {
                    MessageBox.Show("电池阻值恢复成功", "提示");
                }
                else
                {
                    MessageBox.Show("电池阻值恢复失败", "提示", MessageBoxButtons.OK ,MessageBoxIcon.Warning);
                }
            }
            else
                MessageBox.Show("请检查是否链接到电池", "提示");
        }


        //实时数据保存为excel文件
        private void button34_Click_1(object sender, EventArgs e)//实时数据生成文件
        {
            Excel.Application excel = new Excel.Application();
            excel.Application.Workbooks.Add(true);
            excel.Cells[1, 1] = label15.Text;
            for(int head = 0; head < listView1.Columns.Count; ++head)
            {
                excel.Cells[2, head + 1] = listView1.Columns[head].Text;
            }
            for(int col = 0; col < listView1.Columns.Count; ++col)
            {
                for(int row = 0; row < listView1.Items.Count; ++row)
                {
                    excel.Cells[row + 3, col + 1] = listView1.Items[row].SubItems[col].Text;
                }
            }
            excel.Visible = true;
        }


        //单体温度设置

        private void setTemplate(string temp,byte i)//温度表的内容
        {
            if (i >= dataGridView4.RowCount)
            {
                DataGridViewRow row = new DataGridViewRow();
                row.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                row.CreateCells(dataGridView4);
                row.Cells[0].Value = (i + 1).ToString();
                row.Cells[1].Value = temp;
                row.Cells[2].Value = string.Empty;
                row.Cells[3].Value = string.Empty;
                row.Cells[4] = new DataGridViewButtonCell();
                row.Cells[4].Value = "写入";
                row.Cells[5].Value = General;

                dataGridView4.Rows.Add(row);
            }
            else
            {
                dataGridView4.Rows[i].Cells[1].Value = temp;
                dataGridView4.Rows[i].Cells[2].Value = string.Empty;
                dataGridView4.Rows[i].Cells[3].Value = string.Empty;
                dataGridView4.Rows[i].Cells[5].Value = General;
            }
        }

        private void button36_Click(object sender, EventArgs e)//填写全部目标温度
        {
            double result;
            if (double.TryParse(textBox_StdTemp.Text,out result))//(System.Text.RegularExpressions.Regex.IsMatch(textBox_StdTemp.Text, @"^[0-9].$"))
            {
                for (byte i = 0; i < dataGridView4.RowCount; ++i)
                {
                    dataGridView4.Rows[i].Cells[2].Value = textBox_StdTemp.Text;
                    dataGridView4.Rows[i].Cells[3].Value = string.Empty;
                    dataGridView4.Rows[i].Cells[5].Value = General;
                }
            }
            else
                MessageBox.Show("请检查输入格式是否正确", "提示");
        }

        private void button_getTemp_Click(object sender, EventArgs e)//读取实际温度，存放原始温度
        {
            if (!m_isPortOpen)
            {
                MessageBox.Show("串口未打开", "提示");
                return;
            }
            if (dataGridView4.RowCount > 0)
            {
                button_getTemp.Enabled = false;

                int registers = dataGridView4.RowCount;//也是icount，测试单体的个数
                Thread.Sleep(100 + registers * 35);//强制停留，这里设置时间间隔是防止，修改系数还没参与运算，用户就又点击读取

                ushort[] registerhold1 = new ushort[registers * 3 ];//实际温度
                reviseTemp = new ushort[registers];//读取温差修正系数，存放在全局变量里面

                ushort[] tmpBuf1 = new ushort[120];
                ushort[] tmpBuf2 = new ushort[20];

                if (registers <= 40)
                {
                    //温度
                    ModbusRtu.SendFc3(m_iDeviceAddr, 50, (ushort)(registers * 3), ref registerhold1);
                    Thread.Sleep(registers * 35 * 3);
                    //修正系数
                    ModbusRtu.SendFc3(m_iDeviceAddr, 2368, (ushort)((registers + 1) / 2), ref reviseTemp);
                    Thread.Sleep(registers * 35);
                }
                else if (registers > 40 && registers <= 80)
                {
                    //温度
                    ModbusRtu.SendFc3(m_iDeviceAddr, 50, (ushort)(40 * 3), ref tmpBuf1);
                    Thread.Sleep(40 * 35 * 3);
                    //修正系数
                    ModbusRtu.SendFc3(m_iDeviceAddr, 2368, (ushort)((40 + 1) / 2), ref tmpBuf2);
                    Thread.Sleep((ushort)((40 + 1) / 2) * 35);
                    //内存拷贝
                    Array.Copy(tmpBuf1, 0, registerhold1, 0, 120);
                    Array.Copy(tmpBuf2, 0, reviseTemp , 0, 20);

                    //温度
                    ModbusRtu.SendFc3(m_iDeviceAddr,170, (ushort)((registers- 40) * 3), ref tmpBuf1);
                    Thread.Sleep((registers - 40) * 35 * 3);
                    //修正系数
                    ModbusRtu.SendFc3(m_iDeviceAddr, 2388, (ushort)((registers- 40 + 1) / 2), ref tmpBuf2);
                    Thread.Sleep(((registers - 40 + 1) / 2) * 35);
                    //内存拷贝
                    Array.Copy( tmpBuf1, 0, registerhold1, 120, (ushort)((registers - 40) * 3));
                    Array.Copy(tmpBuf2, 0, reviseTemp, 20, (registers - 40 + 1) / 2);



                }
                else if (registers > 80)
                {
                    //温度
                    ModbusRtu.SendFc3(m_iDeviceAddr, 50, (ushort)(40 * 3), ref tmpBuf1);
                    Thread.Sleep(registers * 35 * 3);
                    //修正系数
                    ModbusRtu.SendFc3(m_iDeviceAddr, 2368, (ushort)((40 + 1) / 2), ref tmpBuf2);
                    Thread.Sleep(registers * 35);
                    //内存拷贝
                    Array.Copy( tmpBuf1, 0, registerhold1, 0, 120);
                    Array.Copy( tmpBuf2, 0, reviseTemp, 0, 20);

                    //温度
                    ModbusRtu.SendFc3(m_iDeviceAddr, 170, (ushort)(40 * 3), ref tmpBuf1);
                    Thread.Sleep(40 * 35 * 3);
                    //修正系数
                    ModbusRtu.SendFc3(m_iDeviceAddr, 2388,20, ref tmpBuf2);
                    Thread.Sleep(20 * 35);
                    //内存拷贝
                    Array.Copy( tmpBuf1, 0, registerhold1, 120, 120);
                    Array.Copy( tmpBuf2, 0, reviseTemp, 20, 20);

                    //温度
                    ModbusRtu.SendFc3(m_iDeviceAddr, 290, (ushort)((registers- 80) * 3), ref tmpBuf1);
                    Thread.Sleep((registers - 80) * 35 * 3);
                    //修正系数
                    ModbusRtu.SendFc3(m_iDeviceAddr, 2408,(ushort)((registers-80+1)/2), ref tmpBuf2);
                    Thread.Sleep((registers - 80 + 1)/2 * 35);
                    //内存拷贝
                    Array.Copy( tmpBuf1, 0, registerhold1, 240, ((registers - 80) * 3));
                    Array.Copy( tmpBuf2,0, reviseTemp, 40, (registers - 80 + 1) / 2);

                }

                

                //2.2.处理温差
                ushort tempActual;
                ushort tempGap;
                originalTemp = new double[registers];
                for (int index = 0; index < registers; ++index)
                {
                    //显示读取温度
                    tempActual = registerhold1[1 + 3 * index];//整数
                    dataGridView4.Rows[index].Cells[1].Value = ((double)tempActual / 10).ToString("0.0");
                    dataGridView4.Rows[index].Cells[3].Value = string.Empty;
                    dataGridView4.Rows[index].Cells[5].Value = General;
                    //处理温差
                    tempGap = index % 2 == 0 ? (ushort)(reviseTemp[index / 2] & 255) : (ushort)(reviseTemp[index / 2] >> 8); //【bat2】【bat1】

                    //计算出原始温度
                    originalTemp[index] = (double)tempActual / 10 - tempGap + 10;
                }
                button_getTemp.Enabled = true;
            }
        }

        private string calculateTemp(int index)
        {
            ushort tempGap = (ushort)Math.Round(Convert.ToDouble(dataGridView4.Rows[index].Cells[2].Value) - originalTemp[index] + 10);//计算的修正系数
            Color color ;
            //修正系数在0-20之间,不符合给出颜色提示
            if (tempGap > 20 | tempGap < 0)
            {
                color = Color.Red;
            }
            else
            {
                color = Color.Black;
            }
            dataGridView4.Rows[index].Cells[3].Style.ForeColor = color;

            return tempGap.ToString();
        }

        private bool judge_ArmTempisLost()//判断如果目标温度缺失
        {
            for (int i = 0; i < dataGridView4.RowCount; ++i)
            {
                if (dataGridView4.Rows[i].Cells[2].Value.ToString() == string.Empty)
                {
                    return false;
                }
            }
            return true;
        }

        private void button37_Click(object sender, EventArgs e)//温差一次性刷新，计算温差
        {
            if (!m_isPortOpen)
            {
                MessageBox.Show("串口未打开", "提示");
                return;
            }
            if (!judge_ArmTempisLost())//目标温度存在缺失就不能点击
            {
                MessageBox.Show("目标温度存在缺失，请检查");
                return;
            }

            if (dataGridView4.RowCount > 0)
            {
                //预防处理
                button37.Enabled = false;
                //读取实际温度，存放原始温度
                button_getTemp_Click(null, null);
                //计算全部电池的温差
                for (int index = 0; index < dataGridView4.RowCount; ++index)
                {
                    dataGridView4.Rows[index].Cells[3].Value = calculateTemp(index);
                }
                button37.Enabled = true;
            }   
        }

        private void dataGridView4_CellEndEdit(object sender, DataGridViewCellEventArgs e)//单个编辑完自动计算
        {
            if (!m_isPortOpen)
            {
                MessageBox.Show("请检查串口是否打开");
                return;
            }
            if (e.ColumnIndex == 2)//目标温度
            {
                if (originalTemp ==null | reviseTemp == null )
                {
                    MessageBox.Show("请点击左上方“获取温度”的按钮，获取原始温度和修正系数");
                }
                else if ( originalTemp.Length != dataGridView4.RowCount |  reviseTemp.Length != dataGridView4.RowCount)
                {
                    MessageBox.Show("请点击左上方“获取温度”的按钮，获取原始温度和修正系数");
                }
                else
                {
                    //清空状态
                    dataGridView4.Rows[e.RowIndex].Cells[5].Value = General;
                    //获取原始数据,目标温度编辑回车后，计算出修正系数
                    dataGridView4.Rows[e.RowIndex].Cells[3].Value = calculateTemp(e.RowIndex);
                }
            } 
        }

        private void dataGridView4_CellClick(object sender, DataGridViewCellEventArgs e)//单个温差编辑完，点击写入
        {
            if (!m_isPortOpen)
            {
                MessageBox.Show("串口未打开", "提示");
                return;
            }
            if (e.ColumnIndex == 4 )
            {  
                //警告
                if (dataGridView4.Rows[e.RowIndex].Cells[3].Style.ForeColor == Color.Red)//这里处理的原因是字体是红色已经给出判断
                {
                    MessageBox.Show("系数设置必须在0-20之间", "警告");
                    return;
                }
                if (dataGridView4.Rows[e.RowIndex].Cells[3].Value.ToString() == string.Empty)
                {
                    MessageBox.Show("存在修正系数缺失", "警告");
                    return;
                }


                //1.处理数据
                ushort start = (ushort)(2368 + e.RowIndex / 2);//寄存器地址
                ushort[] registerhold = new ushort[1] { reviseTemp[e.RowIndex / 2] };//提取寄存器的值
                ushort tempGap = Convert.ToUInt16(dataGridView4.Rows[e.RowIndex].Cells[3].Value);//修正系数
                if (e.RowIndex % 2 == 0)//在低位
                {
                    registerhold[0] = (ushort)(registerhold[0] & 0xFF00);
                    registerhold[0] += tempGap;
                }
                else//在高位
                {
                    registerhold[0] = (ushort)(registerhold[0] & 0xFF);
                    registerhold[0] += (ushort)(tempGap << 8);
                }

                //2.发送指令
                bool bhold = ModbusRtu.SendFc6(m_iDeviceAddr, start, 1, registerhold);

                //3.反馈
                if (bhold)
                {
                    //修改全局变量存放
                    reviseTemp[e.RowIndex / 2] = registerhold[0];

                    //强制等待35ms，确保用户无时间间隔点击发送按钮仍然可以正确读数
                    Thread.Sleep(35);

                    dataGridView4.Rows[e.RowIndex].Cells[5].Value = Success;
                    dataGridView4.Rows[e.RowIndex].Cells[5].Style.ForeColor = Color.Green;
                }
                else
                {
                    dataGridView4.Rows[e.RowIndex].Cells[5].Value = Failure;
                    dataGridView4.Rows[e.RowIndex].Cells[5].Style.ForeColor = Color.Red;
                }
            }
        }

        private bool judge_ReviseTempisLost()//修正温差的系数是否缺失
        {
            bool hbold = true;
            for (int i = 0; i < dataGridView4.RowCount; ++i)
            {
                if (dataGridView4.Rows[i].Cells[3].Value.ToString() == string.Empty)
                {
                    return false;
                }
            }
            return hbold;
        }

        private bool judge_ReviseTempisOutBorder()//修正温差的系数在0-20
        {
            bool hbold = true;
            for(int i=0;i< dataGridView4.RowCount; ++i)
            {
                if (Convert.ToUInt16(dataGridView4.Rows[i].Cells[3].Value) > 20 | Convert.ToUInt16(dataGridView4.Rows[i].Cells[3].Value) < 0)
                {
                    return false;
                }
            }
            return hbold;
        }

        private void button_setAllTemp_Click(object sender, EventArgs e)//一次性全部写入全部的修正系数
        {
            if (!m_isPortOpen)
            {
                MessageBox.Show("串口未打开", "提示");
                return;
            }
            if (!judge_ReviseResistanceisLost2())//修正温差的系数不在0-20，不进行发送
            {
                MessageBox.Show("存在修正系数缺失，请检查");
                return;
            }
            if (!judge_ReviseTempisOutBorder())//修正温差的系数不在0-20，不进行发送
            {
                MessageBox.Show("存在修正系数不在0-20范围内，请检查");
                return;
            }

            if (dataGridView4.RowCount > 0)
            {
                

                int icount = dataGridView4.RowCount;//bat数量
                int registers = (icount + 1) / 2;
                ushort[] registerhold = new ushort[registers];
                ushort[] tmpBuf = new ushort[40];
                for(int index = 0; index < icount; ++index)
                {
                    registerhold[index / 2] += index % 2 == 0 ? (ushort)(Convert.ToInt16(dataGridView4.Rows[index].Cells[3].Value)) : (ushort)(Convert.ToInt16(dataGridView4.Rows[index].Cells[3].Value) << 8);
                }
                Console.WriteLine("+:"+registers.ToString());
                //如果时奇数个bat，在最后一个寄存器前加上0x0a
                if (icount % 2 == 1)
                    registerhold[registers - 1] += 0x0a00;

                bool hbold = false;
                if (icount <= 40)
                {
                    hbold = ModbusRtu.SendFc16(m_iDeviceAddr, 2368, (ushort)registers, registerhold);
                    Console.WriteLine("1:"+hbold.ToString());
                }
                if (icount > 40 && icount <= 80)
                {
                    Array.Copy(registerhold, 0, tmpBuf, 0, 20);
                    hbold = ModbusRtu.SendFc16(m_iDeviceAddr, 2368, (ushort)20, tmpBuf);
                    Console.WriteLine("2:" + hbold.ToString());

                    Array.Copy(registerhold, 20, tmpBuf, 0, registers - 20);
                    hbold = ModbusRtu.SendFc16(m_iDeviceAddr, 2388, (ushort)(registers - 20), tmpBuf);
                    Console.WriteLine("3:" + hbold.ToString());

                }
                else if (icount > 80)
                {
                    Array.Copy(registerhold, 0, tmpBuf, 0, 20);
                    hbold = ModbusRtu.SendFc16(m_iDeviceAddr, 2368, (ushort)20, tmpBuf);
                    Console.WriteLine("4:" + hbold.ToString());
                    Array.Copy(registerhold, 20, tmpBuf, 0, 20);
                    hbold = ModbusRtu.SendFc16(m_iDeviceAddr, 2388, (ushort)20, tmpBuf);
                    Console.WriteLine("5:" + hbold.ToString());
                    Array.Copy(registerhold, 40, tmpBuf, 0, registers - 40);
                    hbold = ModbusRtu.SendFc16(m_iDeviceAddr, 2408, (ushort)(registers - 40), tmpBuf);
                    Console.WriteLine("6:" + hbold.ToString());


                }
                Thread.Sleep(1000 + registers * 35);

                Color color = (hbold) ? Color.Green : Color.Red;
                string str = (hbold) ? Success : Failure;
                for (int i = 0; i < icount; ++i)
                {
                    dataGridView4.Rows[i].Cells[5].Style.ForeColor = color;
                    dataGridView4.Rows[i].Cells[5].Value = str ;
                }
            }
        }

        private void button44_Click(object sender, EventArgs e)//温差中修正系数的恢复
        {
            if (!m_isPortOpen)
            {
                MessageBox.Show("串口未打开", "提示");
                return;
            }
            if (dataGridView4.RowCount > 0)
            {
                int icount = dataGridView4.RowCount;//电池个数

                //1.处理数据
                ushort registers = (ushort)((icount + 1) / 2);//寄存器个数
                ushort[] registerhold = new ushort[registers];
                for (int i = 0; i < registers; ++i)
                    registerhold[i] = 0x0a0a;

                //2.发送数据
                bool bhold = ModbusRtu.SendFc16(m_iDeviceAddr, 2368, registers, registerhold);
                if (bhold)
                {
                    MessageBox.Show("电池温度恢复成功", "提示");
                }
                else
                {
                    MessageBox.Show("电池温度恢复失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
                MessageBox.Show("请检查是否链接到电池", "提示");
        }



        //历史数据查询

        //根据计算时间差，计算组数
        private bool calculateGroup(DateTime dateBegin,DateTime dateEnd,ushort timeGap,ref ushort min,ref ushort max)//开始时间，结束时间 
        {
            bool ret = false;
            ushort[] recv = new ushort[7];
            ret=ModbusRtu.SendFc3(m_iDeviceAddr,2100,7,ref recv);

            if (!ret)
            {
                MessageBox.Show("读取系统时间失败，请重试");
                return false;
            }
           
            DateTime now = new DateTime(recv[0], recv[1], recv[2], recv[4], recv[5], recv[6]);
            //MessageBox.Show(now.ToString());
            DateTime begine = new DateTime(dateBegin.Year, dateBegin.Month, dateBegin.Day, 00, 00, 00);
            DateTime end = new DateTime(dateEnd.Year, dateEnd.Month, dateEnd.Day, 23, 59, 59);
            if (end > now)
                end = now;
            TimeSpan ts0 = new TimeSpan(now.Ticks);
            TimeSpan ts1 = new TimeSpan(begine.Ticks);
            TimeSpan ts2 = new TimeSpan(end.Ticks);

            min = (ushort)(ts0.Subtract(ts2).TotalMinutes / timeGap);
            max = (ushort)(ts0.Subtract(ts1).TotalMinutes / timeGap);
            if (max <= 0)
                max = 1;
            if (min <= 0)
                min = 1;
            return true;
        }

        private string getWarningType(int type)
        {
            switch (type)
            {
                case 1: return "总电压过压报警状态";
                case 2: return "总电压欠压报警状态";
                case 3: return "电池组放电电流过流";
                case 4: return "电池组充电电流过流";
                case 5: return "环境温度1报警状态";
                case 6: return "单节电池过压报警总状态";
                case 7: return "单节电池欠压报警总状态";
                case 8: return "单节电池温度过温报警总状";
                case 9: return "单节电池内阻过高报警总状态";
                case 10: return "单节电池电压高于平均值报警总状态";
                case 11: return "单节电池电压低于平均值报警总状态";
                case 12: return "单节电池内阻高于平均值报警总状态";
                case 13: return "电池内阻测试仪通讯故障报警总状态";
                case 14: return "电流传感器通讯故障报警状态 / 电流传感器接线故障报警状态";
                case 15: return "电池内阻测试仪自身故障使能 / 电池内阻测试仪接线故障";
                case 16: return "电池组容量过低报警状态";
                case 17: return "单节电池容量过低报警状态";
                case 18: return "电压变送器BAT6.1_VT（或VC）通讯状态";
                case 19: return "电池组热失控报警状态";
                case 20: return "KO模块通讯状态";
                default: return "";
            }
        }

        private bool judgeErrorType(ushort type, ref ushort timesBegin, ref ushort timesEnd)//检查边界
        {
            int timesStd;
            switch (type)
            {
                case 1:
                case 2:
                case 3:
                case 4:
                    timesStd = 3000;
                    break;
                default:
                    timesStd = 3000;
                    break;
            }
            if (timesEnd > timesStd)
                return false;
            else if (timesBegin > timesStd) timesBegin = (ushort)timesStd;
            return true;
        }

        private void insertDataGridView5_0(ushort i, ushort[] registerhold)//写表，报警
        {
            int year = (registerhold[0] >> 8) + 2000;
            int month = registerhold[0] & 255;
            int day = registerhold[1] >> 8;
            int hour = registerhold[1] & 255;
            int minute = registerhold[2] >> 8;
            int second = registerhold[2] & 255;
            try
            {
                DataGridViewRow row0 = new DataGridViewRow();
                row0.CreateCells(dataGridView5);
                row0.Cells[0].Value = i;
                row0.Cells[1].Value = year + "年"+month + "月"+day + "日"+hour + "时"+ minute + "分"+second + "秒";
           
                row0.Cells[2].Value = getWarningType(registerhold[3] >> 8);  //告警类型
                row0.Cells[3].Value = registerhold[3]&0xff;                  //设备号
                int warningNumber = (registerhold[4] >> 8) & 0xff;           //告警数值
                row0.Cells[4].Value = warningNumber.ToString();
                dataGridView5.Rows.Add(row0);
            }
            catch (System.ArgumentOutOfRangeException e)
            {
                throw e;
            }

            int rowCount = dataGridView5.Rows.Count;

            // 将滚动条滚动到最后一行
            dataGridView5.FirstDisplayedScrollingRowIndex = dataGridView5.Rows.Count - 1;
            dataGridView5.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells); // 根据单元格内容自动调整列宽
        }

        private void insertDataGridView5(ushort i, ushort[] registerhold)//写表  2-4报警类型 重载
        {
            if (registerhold[0] == 0xffff)
            {
                //MessageBox.Show("0xffff");
                return;
            }
            else
            {
                try
                {
                    DataGridViewRow row0 = new DataGridViewRow();
                    row0.CreateCells(dataGridView5);
                    row0.Cells[0].Value = "第" + i + "组";
                    row0.Cells[1].Value = ((registerhold[0] >> 8)+2000) + "年";
                    row0.Cells[2].Value = (registerhold[0] & 255) + "月";
                    row0.Cells[3].Value = (registerhold[1] >> 8) + "日";
                    row0.Cells[4].Value = (registerhold[1] & 255) + "时";
                    row0.Cells[5].Value = (registerhold[2] >> 8) + "分";
                    row0.Cells[6].Value = (registerhold[2] & 255) + "秒";
                    dataGridView5.Rows.Add(row0);

                    for (int index = 0; index < 120; index += 5)//24行  120个数据，每行5个数据
                    {
                        DataGridViewRow row = new DataGridViewRow();
                        row.CreateCells(dataGridView5);
                        for (int j = 0; j < 5; ++j)
                        {
                            row.Cells[j * 2].Value = (index + j + 1) + "#";
                            row.Cells[j * 2 + 1].Value = registerhold[index+3+j];//(((registerhold[index + j + 3] & 0xFF) << 8) + (registerhold[index + j + 4] >> 8)).ToString();
                        }
                        dataGridView5.Rows.Add(row);
                    }
                    // 将滚动条滚动到最后一行
                    dataGridView5.FirstDisplayedScrollingRowIndex = dataGridView5.Rows.Count - 1;
                    dataGridView5.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells); // 根据单元格内容自动调整列宽
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }

        //
        private DateTime getDateTime(ushort[] registerhold)
        {
            int year = (registerhold[0] >> 8) + 2000;
            int month = registerhold[0] & 255;
            int day = registerhold[1] >> 8;
            int hour = registerhold[1] & 255;
            int minute = registerhold[2] >> 8;
            int second = registerhold[2] & 255;
            DateTime dateTime = new DateTime(year, month, day, hour, minute, second);
            return dateTime;
        }

        //查找边界值
        private ushort getBorderTimes(DateTime date)
        {
            ushort timesBegin = 1000;
            ushort timesEnd = 1;
            ushort[] mid = new ushort[1];
            ushort[] registerhold = new ushort[3];
            while (timesBegin >= timesEnd)
            {
                mid[0] = (ushort)((timesBegin + timesEnd) / 2);
                ModbusRtu.SendFc6(m_iDeviceAddr, 5002, 1, mid);
                Thread.Sleep(35);
                ModbusRtu.SendFc3(m_iDeviceAddr, 5003, 3, ref registerhold);

                if (registerhold[0] == 0xFFFF)
                {
                    timesBegin = mid[0];
                }
                else
                {
                    DateTime getDate = getDateTime(registerhold);
                    if (getDate == date)    //(getDate == date) 基本上用不上
                        return mid[0];
                    if (getDate > date)
                        timesBegin = (ushort)(mid[0]+1);
                    if (getDate < date)
                        timesEnd = (ushort)(mid[0]-1);
                }
            }
            return mid[0];
        }

        private void button39_Click_Logic0()//查询报警
        {
            isRunningHistory0 = true;
            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            try
            {
                //表头初始化
                if (strLang == "ChineseSimplified")
                {
                    dataGridView5.Rows.Clear();
                    dataGridView5.Columns.Clear();
                    dataGridView5.Columns.Add("column1", "数据记录序号");
                    dataGridView5.Columns.Add("column2", "时间");
                    dataGridView5.Columns.Add("column3", "告警类型");
                    dataGridView5.Columns.Add("column4", "告警设备号");
                    dataGridView5.Columns.Add("column5", "告警数值");
                    label154.Text = "等待";
                }
                else
                {
                    dataGridView5.Rows.Clear();
                    dataGridView5.Columns.Clear();
                    dataGridView5.Columns.Add("column1", "data record Serial");
                    dataGridView5.Columns.Add("column2", "time");
                    dataGridView5.Columns.Add("column3", "warning type");
                    dataGridView5.Columns.Add("column4", "warning device id");
                    dataGridView5.Columns.Add("column5", "warnning value");
                    label154.Text = "Wait";

                }
                
                //获得选取得时间值
                DateTime date1 = (dateTimePicker3.Value.Date <= dateTimePicker4.Value.Date) ? dateTimePicker3.Value.Date : dateTimePicker4.Value.Date;
                DateTime date2 = (dateTimePicker3.Value.Date > dateTimePicker4.Value.Date) ? dateTimePicker3.Value.Date : dateTimePicker4.Value.Date;


                //写入要读的历史数据类型
                ushort[] registerhold1 = new ushort[1] { 0 };//0
                bool hbold1 = ModbusRtu.SendFc6(m_iDeviceAddr, 5001, 1, registerhold1);
                if (!hbold1)
                {
                   // MessageBox.Show("error hbold1!");

                }

                Thread.Sleep(35);
                
                //获取时间对应的历史数据序号区间
                ushort max = GetMaxRecordNumber(date2);//获取最大时间的序号临界值
                ushort min = GetMinRecordNumber(date1);//获取最小时间的序号临界值
                if (min == 10000 || max == 10000)
                    goto END;
                if (min <= 0)
                {
                    if (strLang == "ChineseSimplified")
                    {
                        MessageBox.Show("查询完毕");
                        button39.Text = "查询";
                    }
                    else
                    {
                        MessageBox.Show("inquire complete");
                        button39.Text = "inquire";
                    }
                   goto END;
                }
                //根据获得的序号区间读取历史数据并插入表格中
                ushort[] recv = new ushort[7];
                for (ushort i = max; i <= min; i++)
                {
                    if (isRunningHistory0 == false)
                        goto END;
                    ushort[] tmp = new ushort[1];
                    tmp[0] = i;
                    hbold1 = ModbusRtu.SendFc6(m_iDeviceAddr, 5002, 1, tmp);
                    if (!hbold1)
                    {
                     //   MessageBox.Show("error hbold2!"+tmp[0].ToString());
                    }
                    Thread.Sleep(35);
                    bool ret = false;
                    ret = ModbusRtu.SendFc3(m_iDeviceAddr, 5003, 7, ref recv);
                    Thread.Sleep(35);
                    if (ret)
                    {
                        Invoke(new SetDataGridView5(insertDataGridView5_0),new object[] { i, recv });
                    }
                    else
                    {
                      //  MessageBox.Show("error hbold3!");
                    }
                }
                if (strLang == "ChineseSimplified")
                {
                    MessageBox.Show("查询完毕");
                    button39.Text = "查询";
                }
                else
                {
                    MessageBox.Show("inquire complete");
                    button39.Text = "inquire";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }           
            END:
            button39.Enabled = true;
            return;

        }
        UInt16 GetMaxRecordNumber(DateTime date)
        {
            UInt16[] Max = { 1 };
            ushort[] recv = new ushort[3];
            for (int i = 1; i <= 1000; i++)
            {
                if (isRunningHistory0 == false)
                    return 10000;
                ModbusRtu.SendFc6(m_iDeviceAddr, 5002, 1, Max);
                Thread.Sleep(35);
                ModbusRtu.SendFc3(m_iDeviceAddr, 5003, 3, ref recv);
                //读取出来的时间比当前时间大
                if (ReadTimeIsLater2(recv, date))
                {
                    Max[0]++;
                }
                else
                {
                    //读取出来的时间比当前时间小
                    break;
                }
            }    
            return Max[0];

        }
        //获取传入的数据记录id，id对应的时间大于等于选择的日期
        UInt16 GetMinRecordNumber(DateTime date)
        {
            UInt16 ret=1;

            UInt16[] min = {  1};
            ushort[] recv = new ushort[3];
            for(int i=1;i<=1000;i++)
            {
                if (isRunningHistory0 == false)
                    return 10000;
                ModbusRtu.SendFc6(m_iDeviceAddr, 5002, 1, min);
                label166.Text = min[0].ToString();
                Thread.Sleep(35);
                ModbusRtu.SendFc3(m_iDeviceAddr, 5003, 3, ref recv);
                if (ReadTimeIsLater(recv, date))
                {
                    min[0]++;
                }
                else
                {
                    min[0]--;
                    break;
                }
            } 
            return min[0];
        }
        bool ReadTimeIsLater(ushort[] recv, DateTime date)
        {
            bool ret = false;

            if (recv[0] == 0xffff)
                return false;

            int year, mounth, day;
            year = ((recv[0] & 0xff00) >> 8) + 2000;
            mounth = recv[0] & 0x00ff;
            day = ((recv[1] & 0xff00) >> 8);
            
            if (mounth <= 0 || day <= 0 || year <= 0)
                return true;
            DateTime customDate = new DateTime(year, mounth, day, 23, 59, 59);
            if (customDate > date)
            {
                ret = true;
            }
            else
            {
                ret = false;
            }

            return ret;
        }
        bool ReadTimeIsLater2(ushort[] recv, DateTime date)
        {
            bool ret = false;

            if (recv[0] == 0xffff)
                return false;

            int year, mounth, day;
            year = ((recv[0] & 0xff00) >> 8) + 2000;
            mounth = recv[0] & 0x00ff;
            day = ((recv[1] & 0xff00) >> 8);

            if (mounth <= 0 || day <= 0 || year <= 0)
                return true;
            DateTime customDate = new DateTime(year, mounth, day, 00, 00, 00);
            if (customDate > date)
            {
                ret = true;
            }
            else
            {
                ret = false;
            }

            return ret;
        }
        bool ReadTimeIsEarly(ushort[] recv,DateTime date)
        {
            bool ret=false;
            if (recv[0] == 0xffff)
                return true;

            int year, mounth, day;
            year = ((recv[0] & 0xff00) >> 8)+2000;
            mounth = recv[0] & 0xff;
            day= ((recv[1] & 0xff00) >> 8);

            //Console.WriteLine(year.ToString()+","+day.ToString()+","+mounth.ToString());
            if (mounth <= 0 || day <= 0 || year <= 0)
                return true;
            DateTime customDate = new DateTime(year, mounth, day, 12, 00, 00);
            if (customDate < date)
            {
                ret = true;
            }
            else
            {
                ret = false;
            }

            return ret;
        }

        private void button39_Click_Logic()//查询历史数据，除了报警
        {
            try
            {
                isRunningHistory0 = true;
                //初始化表头
                dataGridView5.Rows.Clear();
                dataGridView5.Columns.Clear();
                for (int i = 1; i <= 5; i++)
                {
                    String columnName = String.Format("Column{0}", i * 2);
                    dataGridView5.Columns.Add(columnName, "序号");
                    columnName = String.Format("Column{0}", i * 2 + 1);
                    dataGridView5.Columns.Add(columnName, "值");
                    dataGridView5.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells); // 根据单元格内容自动调整列宽
                }

                label154.Text = "等待";
                //计算历史数据序号
                ushort min = 0, max = 0;
                ushort[] timeGap = new ushort[1];
                DateTime date1 = (dateTimePicker3.Value.Date <= dateTimePicker4.Value.Date) ? dateTimePicker3.Value.Date : dateTimePicker4.Value.Date;
                DateTime date2 = (dateTimePicker3.Value.Date > dateTimePicker4.Value.Date) ? dateTimePicker3.Value.Date : dateTimePicker4.Value.Date;
                bool hbold = ModbusRtu.SendFc3(m_iDeviceAddr, 5000, 1, ref timeGap);
                if (hbold)
                {
                    //MessageBox.Show(timeGap[0].ToString());
                    hbold = calculateGroup(date1, date2, timeGap[0], ref min, ref max);
                    if (!hbold)
                    {
                        MessageBox.Show("计算历史数据序号数失败");
                    }
                }
                else
                {
                    MessageBox.Show("读取历史数据时间间隔失败");
                    return;
                }
                Thread.Sleep(10);

                //1.先写数据类型
                ushort[] registerhold1 = new ushort[1];
                registerhold1[0] = (ushort)(comboBox_historyType.SelectedIndex);
                bool hbold1 = ModbusRtu.SendFc6(m_iDeviceAddr, 5001, 1, registerhold1);
                Thread.Sleep(35);

                //2.数据记录序号和记录数据
                ushort[] recvData = new ushort[123];
                ushort[] historyCnt = new ushort[1];
                for (ushort i = min; i <= max; i++)
                {
                    if (!isRunningHistory0)
                    {
                        //MessageBox.Show("123456");
                        return;
                    }
                    //先写  数据记录序号
                    historyCnt[0] = i;
                    hbold = ModbusRtu.SendFc6(m_iDeviceAddr, 5002, 1, historyCnt);
                    if (!hbold)
                    {
                        MessageBox.Show("设置历史数据序号数失败");
                    }

                    Thread.Sleep(35);
                    //再读
                    hbold = ModbusRtu.SendFc3(m_iDeviceAddr, 5003, 123, ref recvData);
                    Thread.Sleep(35);
                    if (hbold)
                    {
                        Invoke(new SetDataGridView5_1(insertDataGridView5), new object[] { i, recvData });
                    }
                    else
                    {
                        //偶尔读取失败重试
                        if (!(hbold = ModbusRtu.SendFc3(m_iDeviceAddr, 5003, 123, ref recvData)))
                        {
                            MessageBox.Show("读取历史数据失败" + historyCnt[0].ToString());
                            continue;
                        }
                        else
                        {
                            Invoke(new SetDataGridView5_1(insertDataGridView5), new object[] { i, recvData });
                        }
                       
                    }

                }
                label154.Text = "";
                MessageBox.Show("查询完毕");
                button39.Text = "查询";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                button39.Text = "查询";
            }
            isRunningHistory0 = false;
        }



        private void button39_Click(object sender, EventArgs e)//查询历史数据按钮
        {
            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();
            if (!m_isPortOpen)
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("串口未打开", "提示");
                else
                    MessageBox.Show("port not open", "tips"); 
               
                return;
            }
            if (comboBox_historyType.SelectedIndex == -1)
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("请选择查询的历史数据类型", "提示");
                else
                    MessageBox.Show("Select the type of historical data to be queried", "tips"); ;
            }
            else
            {
                /*
                if (thread_poll3 != null & thread_poll3.IsAlive == true)
                {
                    thread_poll3.Abort();
                    Thread.Sleep(10);
                }*/
                if (button39.Text == "查询" || button39.Text == "inquire")
                {
                    if (strLang == "ChineseSimplified")
                        button39.Text = "取消";
                    else
                        button39.Text = "cancle";

                    thread_poll3 = (comboBox_historyType.SelectedIndex == 0) ? new Thread(new ThreadStart(button39_Click_Logic0)) : new Thread(new ThreadStart(button39_Click_Logic));
                    thread_poll3.Start();
                }
                else
                {
                    if (strLang == "ChineseSimplified")
                        button39.Text = "查询";
                    else
                        button39.Text = "inquire";
                    //button39.Enabled = false;
                    isRunningHistory0 = false;
                    label154.Text = string.Empty;

                    //if (!thread_poll3.IsAlive)
                    //{
                    //    button39.Enabled = true;
                    //   // thread_poll3.Abort();
                    //}
                }

            }
        }


        //历史数据2页面
        private void comboBox29_SelectedIndexChanged(object sender, EventArgs e)//选择的历史数据类型改变
        {
            tabpage17Limit();
        }

        private void textBox76_TextChanged(object sender, EventArgs e)//输入电池序号
        {
            tabpage17Limit();
        }

        private void textBox80_TextChanged(object sender, EventArgs e)//输入电池序号
        {
            tabpage17Limit();
        }

        private void tabpage17Limit()//tabpage17输入的限制
        {
            int result;
            Color color = Color.Red;
            int border_min = 1, border_max = 120;
            switch (comboBox29.SelectedIndex)
            {
                case 0://M为0时，N的范围为1~120
                    border_max = 120;
                    break;
                case 1://M为1和2时，N的范围为1~123
                case 2:
                    border_max = 123;
                    break;
            }
            int min=0, max=0;
            if (int.TryParse(textBox80.Text, out result))//输入的是无符号整型
            {
                if (result >= border_min & result <= border_max)//只有在合理范围内的是黑色
                {
                    min = result;
                    color = Color.Black;
                }
            }
            textBox80.ForeColor = color;
            if (int.TryParse(textBox76.Text, out result))//输入的是无符号整型
            {
                if (result >= border_min & result <= border_max)//只有在合理范围内的是黑色
                {
                    max = result;
                    color = Color.Black;
                }
            }
            textBox76.ForeColor = color;

            if (min > max)
            {
                textBox80.ForeColor = Color.Red;
                textBox76.ForeColor = Color.Red;
            }
        }

        private void button47_Click(object sender, EventArgs e)//历史数据2，查询功能
        {
            //获取语言
            Language lang = this.CurrentSelectedLanguage;
            string strLang = lang.ToString();

            //判断串口是否打开
            if (!m_isPortOpen)
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("串口未打开", "提示");
                else
                    MessageBox.Show("serial port not open", "tips"); 
                return;
            }

            //判断输入，历史数据类型或者电池序号是否填写
            if(comboBox29.Text==string.Empty||textBox80.Text == string.Empty||textBox76.Text==string.Empty)
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("历史数据类型或电池序号未填写，请检查", "提示");
                else
                    MessageBox.Show("The historical data type or battery serial number is not entered. Please check", "tips");
                return;
            }

            //判断电池序号是否再合理范围内
            if (textBox80.ForeColor == Color.Red|| textBox76.ForeColor == Color.Red)
            {
                if (strLang == "ChineseSimplified")
                    MessageBox.Show("电池序号不在合理范围内，请检查", "提示");
                else
                    MessageBox.Show("Battery serial number is out of reasonable range, please check", "tips");
                return;
            }

            //清空列表
            listView12.Items.Clear();

            //防止多线程冲突，关闭首页的查询线程（已通过标志位防止冲突）
            //bool isThread_PollRunning = false;
            //if (thread_poll != null)
            //{
            //    if (thread_poll.IsAlive == true)
            //    {
            //        isThread_PollRunning = true;
            //        thread_poll.Abort();
            //        Thread.Sleep(1000);
            //    }
            //}

            //先写入3000寄存器的指令,历史数据类型和电池节数或总平均值
            int startSerial = Convert.ToInt32(textBox80.Text);
            int endSerial = Convert.ToInt32(textBox76.Text);
            for (int f = startSerial; f <= endSerial; f++)
            {
                ushort[] registerhold1 = new ushort[1] { (ushort)((comboBox29.SelectedIndex << 8) +f) };
                bool bhold1 = ModbusRtu.SendFc6(m_iDeviceAddr, 3000, 1, registerhold1);
                Thread.Sleep(35);

                if (bhold1)
                {
                    ushort register = 107;
                    ushort start = 3001;

                    string timeRecord = "采样测量时间";//记录时间的次数，M为0时，只记录最后一次时间；M为1或2时，记录开始和最后两次记录时间
                    string unit = "内阻(mΩ)";
                    string title = "历史内阻条数";

                    if (strLang == "ChineseSimplified")
                    {
                        timeRecord = "采样测量时间";
                        unit = "内阻(mΩ)";
                        title = "历史内阻条数";
                    }
                    else
                    {
                        timeRecord = "Sampling measurement time";
                        unit = "internal resistance(mΩ)";
                        title = "Number of historical internal resistance bars";
                    }
                    int toChangeUnit = 1000;
                    switch (comboBox29.SelectedIndex)
                    {
                        case 0://M为0时，表示为单节内阻历史数据；
                               //register = 107;start = 3001;unit = "内阻(mΩ)";toChangeUnit = 100
                            break;
                        case 1://M为1时，表示为充电状态下单节电压、总电压、总电流的历史数据；
                        case 2://M为2时，表示为放电状态下单节电压、总电压、总电流历史数据
                            register = 112;
                            start = 4001;
                            if (strLang == "ChineseSimplified")
                            {
                                title = "电压曲线采样点数";
                                switch (Convert.ToInt32(textBox80.Text))
                                {
                                    case 122:
                                        unit = "组电流(A)";
                                        toChangeUnit = 10;
                                        title = "电流曲线采样点数";
                                        break;
                                    case 123:
                                        unit = "总电压(V)";
                                        toChangeUnit = 10;
                                        break;
                                    default://1-121
                                        unit = "单体电压(V)";
                                        toChangeUnit = 1000;
                                        break;
                                }
                                break;
                            }
                            else
                            {
                                title = "Voltage curve sampling number";
                                switch (Convert.ToInt32(textBox80.Text))
                                {
                                    case 122:
                                        unit = "Group current(A)";
                                        toChangeUnit = 10;
                                        title = "Current curve sampling number";
                                        break;
                                    case 123:
                                        unit = "total voltage(V)";
                                        toChangeUnit = 10;
                                        break;
                                    default://1-121
                                        unit = "Cell voltage(V)";
                                        toChangeUnit = 1000;
                                        break;
                                }
                                break;

                            }
                            /*
                        default:
                            register = 107;
                            start = 3001;
                            timeCount = 1;
                            break;*/
                    }

                    //读取4001~4112或3001~3107寄存器的值 开始时间，结束时间，电池序号，采样点数，采样值
                    ushort[] registerhold2 = new ushort[register];
                    bool bhold2 = ModbusRtu.SendFc3(m_iDeviceAddr, start, register, ref registerhold2);
                    Thread.Sleep(35);
                    if (bhold2)
                    {
                        int index = 0;

                        ListViewItem OptionItem1 = new ListViewItem(timeRecord);
                        OptionItem1.UseItemStyleForSubItems = false;

                        //测量开始时间
                        if (strLang == "ChineseSimplified")
                        {
                            OptionItem1.SubItems.Add("年");
                            OptionItem1.SubItems.Add(registerhold2[index].ToString()); ++index;
                            OptionItem1.SubItems.Add("月");
                            OptionItem1.SubItems.Add(registerhold2[index].ToString()); ++index;
                            OptionItem1.SubItems.Add("日");
                            OptionItem1.SubItems.Add(registerhold2[index].ToString()); ++index;
                            OptionItem1.SubItems.Add("时");
                            OptionItem1.SubItems.Add(registerhold2[index].ToString()); ++index;
                            OptionItem1.SubItems.Add("分");
                            OptionItem1.SubItems.Add(registerhold2[index].ToString()); ++index;
                            listView12.Items.Add(OptionItem1);
                        }
                        else
                        {
                            OptionItem1.SubItems.Add("year");
                            OptionItem1.SubItems.Add(registerhold2[index].ToString()); ++index;
                            OptionItem1.SubItems.Add("mounth");
                            OptionItem1.SubItems.Add(registerhold2[index].ToString()); ++index;
                            OptionItem1.SubItems.Add("day");
                            OptionItem1.SubItems.Add(registerhold2[index].ToString()); ++index;
                            OptionItem1.SubItems.Add("hour");
                            OptionItem1.SubItems.Add(registerhold2[index].ToString()); ++index;
                            OptionItem1.SubItems.Add("minute");
                            OptionItem1.SubItems.Add(registerhold2[index].ToString()); ++index;
                            listView12.Items.Add(OptionItem1);


                        }


                        //充放电时，只显示开始测量时间，不再记录结束时间
                        if (comboBox29.SelectedIndex != 0)
                        {
                            index += 5;
                        }

                        //电池序号
                        if (strLang == "ChineseSimplified")
                        {
                            ListViewItem OptionItem2 = new ListViewItem("电池序号");
                            OptionItem2.SubItems.Add(registerhold2[index].ToString());
                            ++index;
                            listView12.Items.Add(OptionItem2);
                        }
                        else
                        {
                            ListViewItem OptionItem2 = new ListViewItem("Battery serial number");
                            OptionItem2.SubItems.Add(registerhold2[index].ToString()); ++index;
                            listView12.Items.Add(OptionItem2);
                        }

                        //测量单位
                        ListViewItem OptionItem3 = new ListViewItem(title);
                        OptionItem3.SubItems.Add(registerhold2[index].ToString()); ++index;
                        if (strLang == "ChineseSimplified")
                            OptionItem3.SubItems.Add("测量单位");
                        else
                            OptionItem3.SubItems.Add("measurement unit");

                        OptionItem3.SubItems.Add(unit);
                        listView12.Items.Add(OptionItem3);

                        //设置要显示的内容
                        short[,] registerhold3 = new short[20, 5];//测量值
                        string[,] titlehold = new string[20, 5];//序号
                        for (int j = 0; j < 100; ++j)
                        {
                            registerhold3[j % 20, j / 20] = (short)registerhold2[index]; ++index;
                            titlehold[j % 20, j / 20] = "#" + j.ToString();
                        }
                        if (strLang == "ChineseSimplified")
                        {
                            titlehold[0, 0] = "最后一次";
                            titlehold[1, 0] = "较前1次";
                            titlehold[2, 0] = "较前2次";
                        }
                        else
                        {
                            titlehold[0, 0] = "the last time";
                            titlehold[1, 0] = "last 1 time";
                            titlehold[2, 0] = "last 2 time";
                        }
                        //表格显示 表头和数据
                        for (int row = 0; row < 20; ++row)
                        {
                            ListViewItem OptionItem = new ListViewItem();
                            for (int col = 0; col < 5; ++col)
                            {
                                OptionItem.SubItems.Add(titlehold[row, col]);
                                short ceo = registerhold3[row, col]; ++index;
                                OptionItem.SubItems.Add(((ushort)ceo != 0xffff) ? ((float)ceo / toChangeUnit).ToString() : "0xFFFF");
                            }
                            listView12.Items.Add(OptionItem);
                        }
                    }
                    else
                    {
                        if (strLang == "ChineseSimplified")
                            MessageBox.Show("获取电阻失败");
                        else
                        {
                            MessageBox.Show("Failed to obtain resistance");
                        }
                    }
                }
                else
                {
                    if (strLang == "ChineseSimplified")
                        MessageBox.Show("查询失败");
                    else
                        MessageBox.Show("Query failure");

                }
            }
            //if ( isThread_PollRunning == true)
            //{
            //    thread_poll.Start();
            //}
        }

        private void button48_Click(object sender, EventArgs e)//历史数据2，保存功能
        {
            Excel.Application excel = new Excel.Application();
            excel.Application.Workbooks.Add(true);
            for (int head = 0; head < listView12.Columns.Count; ++head)
            {
                excel.Cells[1, head + 1] = listView12.Columns[head].Text;
            }
            
            foreach(ListViewItem listViewItem in listView12.Items)
            {
                foreach(ListViewSubItem item in listViewItem.SubItems)
                {
                    excel.Cells[listViewItem.Index + 2, listViewItem.SubItems.IndexOf(item) + 1] = item.Text;
                }
            }

            excel.Visible = true;
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton1.Checked)
            {
                textBox9.Text = "2.45";
                textBox8.Text = "1.8";
                textBox58.Text = "2.41";
                textBox57.Text = "1.8";
                textBox56.Text = "2.41";
                textBox55.Text = "2.16";
                textBox54.Text = "2.41";
                textBox53.Text = "1.8";
                textBox52.Text = "2.41";
                textBox51.Text = "2";

                //textBox63.Text = "";
                //textBox62.Text = "";

            }
        }

        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton2.Checked)
            {
                textBox9.Text = "14.5";
                textBox8.Text = "10.8";
                textBox63.Text = "14.1";
                textBox62.Text = "13.5";
                textBox58.Text = "14.5";
                textBox57.Text = "10.8";
                textBox56.Text = "14.5";
                textBox55.Text = "13.2";
                textBox54.Text = "14.5";
                textBox53.Text = "10.8";
                textBox52.Text = "14.5";
                textBox51.Text = "12";

            }
        }

        private void button49_Click(object sender, EventArgs e)
        {
            timer2.Start();
        }

        private void button50_Click(object sender, EventArgs e)
        {
            timer2.Stop();
        }

        private void button51_Click(object sender, EventArgs e)
        {
            Excel.Application excel = new Excel.Application();
            excel.Application.Workbooks.Add(true);
            //第一行 时间
            excel.Cells[1, 1] = label15.Text;
            //第二行 表头
            for (int head = 0; head < dataGridView6.ColumnCount; ++head)
            {
                excel.Cells[2, head + 1] = dataGridView6.Columns[head].HeaderText;
            }
            //第三行内容
            for (int col = 0; col < dataGridView6.ColumnCount; ++col)
            {
                for (int row = 0; row < dataGridView6.Rows.Count; ++row)
                {
                    excel.Cells[row + 3, col + 1] = dataGridView6.Rows[row].Cells[col].Value;
                }
            }
            excel.Visible = true;
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            ushort[] recv=new ushort[2];
            ModbusRtu.SendFc3(m_iDeviceAddr, (ushort)numericUpDown1.Value, 2, ref recv);
            int batterySerial = 0;
            batterySerial = recv[0];

            ushort softversion =recv[1];

            String softWareVeresion;
            softWareVeresion = softversion.ToString().PadLeft(5, '0');
            softWareVeresion=softWareVeresion.Insert(1, ".");
            softWareVeresion=softWareVeresion.Insert(4, ".");

            if (batterySerial == 0)
            {
                return;
            }
            if (batterySerial <= 30)
            {
                dataGridView6.Rows[batterySerial - 1].Cells[1].Value = softWareVeresion;
            }
            else if (batterySerial >= 31 && batterySerial <= 60)
            {
                dataGridView6.Rows[batterySerial -30- 1].Cells[3].Value = softWareVeresion;
            }
            else if (batterySerial >= 61 && batterySerial <= 90)
            {
                dataGridView6.Rows[batterySerial -60- 1].Cells[5].Value = softWareVeresion;
            }
            else if (batterySerial >= 91 && batterySerial <= 120)
            {
                dataGridView6.Rows[batterySerial - 90-1].Cells[7].Value = softWareVeresion;
            }
          // Console.WriteLine(softWareVeresion);
        }

        private void dataGridView6_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void button52_Click(object sender, EventArgs e)
        {
            Excel.Application excel = new Excel.Application();
            excel.Application.Workbooks.Add(true);
            for (int head = 0; head < dataGridView5.ColumnCount; ++head)
            {
                excel.Cells[1, head + 1] = dataGridView5.Columns[head].HeaderText;
            }


            foreach (DataGridViewRow row in dataGridView5.Rows)
            {
                foreach (DataGridViewCell cell in row.Cells)
                {
                    excel.Cells[cell.RowIndex + 2, cell.ColumnIndex+1] = cell.Value;
                    // 处理每个单元格，例如打印出单元格的值
                  //  Console.WriteLine(cell.Value);
                }
            }
            //foreach (ListViewItem listViewItem in listView12.Items)
            //{
            //    foreach (ListViewSubItem item in listViewItem.SubItems)
            //   {
            //       excel.Cells[listViewItem.Index + 2, listViewItem.SubItems.IndexOf(item) + 1] = item.Text;
            //  }
            //}

            excel.Visible = true;
        }

        private void dataGridView5_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (comboBox_historyType.SelectedIndex!=0&&e.RowIndex% 25==0 && e.ColumnIndex!=-1&&e.ColumnIndex!=10)
            {
                // 获取当前单元格的边界
                Rectangle rect = new Rectangle(e.CellBounds.Left, e.CellBounds.Top,
                    e.CellBounds.Width, e.CellBounds.Height);

                using (Brush gridBrush = new SolidBrush(this.dataGridView1.GridColor),
                    backColorBrush = new SolidBrush(e.CellStyle.BackColor))
                {
                    // 清除单元格背景
                    e.Graphics.FillRectangle(backColorBrush, rect);

                    // 画左竖线
                    if(e.ColumnIndex==0)
                        e.Graphics.DrawLine(Pens.Black, e.CellBounds.Left-1, e.CellBounds.Top, e.CellBounds.Left-1, e.CellBounds.Bottom);
                    //画右竖线
                    if (e.ColumnIndex == 9)
                        e.Graphics.DrawLine(Pens.Black, e.CellBounds.Right-1, e.CellBounds.Top, e.CellBounds.Right-1, e.CellBounds.Bottom);
                    //画底线
                    e.Graphics.DrawLine(Pens.Black, e.CellBounds.Left, e.CellBounds.Bottom - 1,e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);
                    //画上线
                    e.Graphics.DrawLine(Pens.Black, e.CellBounds.Left, e.CellBounds.Top - 1,
                        e.CellBounds.Right - 1, e.CellBounds.Top - 1);

                    if (e.ColumnIndex == 3)
                        x1 = e.CellBounds.Left;
                    if (e.ColumnIndex == 7)
                        x2 = e.CellBounds.Right;
                    dateTimeStringInGridView5 = dateTimeStringInGridView5 + e.Value;
                    if (e.ColumnIndex == 9)
                    {
                        Rectangle areaInGridView5 = new Rectangle(x1, e.CellBounds.Top+4, x2 - x1, e.CellBounds.Height);
                        Font newFont = new Font(e.CellStyle.Font, FontStyle.Regular);
                        e.Graphics.DrawString(dateTimeStringInGridView5, newFont,Brushes.Red, areaInGridView5, StringFormat.GenericDefault);
                        dateTimeStringInGridView5 = string.Empty;
                    }
                    

                    // 防止进一步的绘制
                   
                }
                e.Handled = true;
            }
           
        }
    }
}
